2013-04-08 75 views
2

我在將以下內容保存到數據庫時遇到問題。Linq - 不保存在db.SaveChanges()上的對象中的列表調用

我有一個分支列表作爲MessageType對象的一部分。我更新代碼第1節中的分支列表,然後將分支列表保存到第2節中的MessageType對象中,然後調用db.SaveChanges()。不幸的是,新的分支清單並未持續。

// section 1 
List<Branch> myBranches = new List<Branch>(); 
      foreach (int bid in branches) 
      { 
       var bran = db.Branches.Find(bid); 
       if (bran != null) 
       { 
        myBranches.Add(bran); 
       } 
      } 
//section 2 
      try 
      { 

       messagetype.SenderID = eSenderDB.MvcApplication.SenderID; 
       messagetype.Branches = myBranches; 
       foreach (Branch bra in messagetype.Branches) 
       { 
        db.Entry(bra).State = EntityState.Modified; 
        db.SaveChanges(); 

       } 
       //db.Entry(messagetype.Branches).State = EntityState.Modified; 
       db.Entry(messagetype).State = EntityState.Modified; 

       db.SaveChanges(); 

我的創建方法

[HttpPost] 
     public ActionResult Create(MessageType messagetype, int[] branches) 
     { 
      List<Branch> myBranches = new List<Branch>(); 
      foreach (int bid in branches) 
      { 
       var bran = db.Branches.Find(bid); 
       if (bran != null) 
       { 
        myBranches.Add(bran); 
       } 
      } 

      { 
       messagetype.Branches = myBranches; 
       messagetype.SenderID = eSenderDB.MvcApplication.SenderID; 
       messagetype.OptIns = 0; 
       db.MessageTypes.Add(messagetype); 
       db.SaveChanges(); 
       return RedirectToAction("Index"); 
      } 

      return View(messagetype); 
     } 
+0

數據庫結構是這樣的一個分支可以有很多消息類型和一個消息類型可以有很多分支。 – GMan 2013-04-08 14:15:09

回答

1

我猜這兩個方法是MVC中的Create和Edit控制器方法。

這裏的問題是您的MessageType對象直接從HTTP請求通過MVC活頁夾傳遞。所以這是一個ViewModel。同時,您將此對象用作EntityModel。

這有點代碼味道,因爲表示層的需求通常可能會背離數據模型的需求。爲每個對象分開對象會給你一些好處。

要解決這個特定的問題,你有兩個選擇:

// Tell the database context to track the object and that the initial state is modified. 
db.MessageTypes.Attach(messagetype); 
db.MessageTypes(messagetype).State = EntityState.Modified; 

或者,

// Separate the entity object from the view object and merge the changes. 
var messageTypeEntity = db.MessageTypes.Find(messageTypeViewModel.Id); 
if(messageTypeEntity == null) 
{ 
    ModelState.AddModelError(string.Empty, "The specified MessageType could not be found."); 
    return View(messageTypeViewModel); 
} 

// Update messageTypeEntity from messageTypeViewModel 
UpdateModel(messageTypeEntity); 

db.SaveChanges(); 

有一個瞭解System.Web.Mvc.Controller.UpdateModel(...),而且也有點討論的SO here

+0

謝謝 - 解決了它! – GMan 2013-04-09 09:32:53

6

你忘了將其連接到上下文。試試下面的代碼:

foreach (Branch bra in messagetype.Branches) 
{ 
    db.Branches.Attach(bra); 
    db.Entry(bra).State = EntityState.Modified; 
    db.SaveChanges(); 
} 

在一個側面說明,我的問題在你的foreach循環調用SaveChanges。你可以保存到最後,它仍然可以正常工作。

+0

不幸的是,這仍然沒有解決問題。這可能是我的映射嗎?我懷疑它是否是我的映射,因爲在我的創建方法中,我做了類似的工作。 – GMan 2013-04-08 23:36:40

+0

創建方法添加.. – GMan 2013-04-08 23:39:30

+0

感謝您的意見,我應該更明確地說它是編輯方法的一部分。 – GMan 2013-04-09 09:33:35

相關問題