2016-08-18 37 views
0

實體框架問題 - 我正在尋找更有效的方式來更新父和子記錄。ASP.NET實體框架 - 使用附件更新子依賴項

場景 - 我們有一個包含一個或多個子對象的父對象。當父對象得到更新時,我們需要清除所有當前的子記錄並重新添加新的子記錄。

例如:

public bool UpdateProfile(Parent record) 
{ 
     try 
     { 
      _context.Parent.Attach(record);  
      _context.Entry(record).State = EntityState.Modified; 

      List<Child> childrenToDelete = GetChildrenByParentId(parent.Id); 
      foreach (Child child in childrenToDelete) 
      { 
       _context.Child.Remove(child); 
       _context.Entry(child).State = EntityState.Deleted; 
      } 
      foreach (Child child in record.children) 
      { 
       _context.ProfileCategories.Add(child); 
      } 
      _context.SaveChanges(); 
      return true; 
} 
     ... 
    } 

上述代碼在「_context.Parent.Attach(記錄)」行拋出異常說,有記錄的重複的ID。所以我們的工作是:

public bool UpdateProfile(Parent record) 
{ 
    try 
    { 
     var originalChildren = record.children; 
     record.children = new List<Child>(); 
     _context.Parent.Attach(record);  
     _context.Entry(record).State = EntityState.Modified; 
     _context.SaveChanges(); 

     List<Child> childrenToDelete = GetChildrenByParentId(parent.Id); 
     foreach (Child child in childrenToDelete) 
     { 
      _context.Child.Remove(child); 
      _context.Entry(child).State = EntityState.Deleted; 
     } 
     foreach (Child child in originalChildren) 
     { 
      _context.ProfileCategories.Add(child); 
     } 
     _context.SaveChanges(); 
     return true; 
    } 
    ... 
} 

這第二塊代碼的作品,但我只是覺得它不理想。

任何人都可以告訴我們爲什麼Attach會拋出重複的Id異常,如果我們擁有的解決方案是處理此問題的最佳方法?

回答

0

未經檢驗的,但我要拍的是這樣的:

public void UpdateProfile(Parent record) 
    { 
     using(var db = new MyContext()) 
     { 
      var children = db.Children.Where(x => x.ParentId == record.Id); 
      db.ProfileCategories.AddRange(children); 
      db.Children.RemoveRange(children); 
      db.SaveChanges(); 
     } 
    }