2011-12-01 33 views
0

使用MVC創造型球員的數據庫條目:爲什麼使用SubmitChanges時數據不存儲?

[HttpPost] 
public ActionResult Create(FormCollection fc, Player player) 
{ 
    players.Players.InsertOnSubmit(player); 
    players.SubmitChanges(); 

    Errors errors; 
    if (!IsValid(player, out errors)) 
    { 
     ViewBag.Errors = errors; 
     return RedirectToAction("Edit", player); 
    } 

    return Redirect("/Home/Players"); 
} 

[HttpPost] 
public ActionResult Edit(FormCollection fc, Player player) 
{ 
    players.SubmitChanges(); 

    return Redirect("/Home/Players"); 
} 

我的問題是players.SubmitChanges()的編輯方法不會更改數據庫中的任何東西。在創作中使用InsertObSubmit。我可以用另一種方式來做嗎?

+2

'player'沒有連接到數據庫。此外,這與MVC無關,但與Linq-to-SQL或Entity Framework相關。 :) – bzlm

+0

我該如何以及在哪裏將播放器附加到數據庫?因爲Player具有global :: System.Data.Linq.Mapping.TableAttribute(Name)屬性集,所以我會假設它知道它屬於哪裏。 –

回答

0

當你得到一個球員值作爲編輯操作的輸入參數,你應該先修改您的收藏players - 這不會自動發生 - 然後才做players.SubmitChanges();

+0

你是什麼意思'相應地修改你的球員收藏'?我如何做到這一點,在代碼中? –

+0

抱歉,延誤; @Akash已經給出了答案 –

1
[HttpPost] 
public ActionResult Edit(FormCollection fc, Player player) 
{ 
    // I guess you are forgetting this 
    players.Players.AttachAsModified(player) 

    players.SubmitChanges(); 

    return Redirect("/Home/Players"); 
} 
+0

玩家中沒有這樣的方法。只有Attach()和AttachAll()。如果我使用Attach()並將asModified設置爲true,則會得到異常「System.InvalidOperationException:如果實體只聲明版本成員或者沒有更新檢查策略,則只能在未經原始狀態修改的情況下進行修改」。 –

+0

你可以試試這個,http://geekswithblogs.net/michelotti/archive/2009/11/27/attaching-modified-entities-in-ef-4.aspx? –

相關問題