2016-08-18 8 views
0

Entity Frameworkに関する質問 - 私は親子レコードをより効率的に更新する方法を探しています。ASP.NETエンティティフレームワーク - 添付ファイルで子依存関係を更新する

シナリオ - 1つまたは複数の子オブジェクトを含む親オブジェクトがあります。親オブジェクトが更新されると、現在のすべての子レコードをクリアし、新しい子レコードを再追加する必要があります。例えば

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; 
} 
     ... 
    } 

上記のコードは、レコードの重複Idsがあるという「_context.Parent.Attach(レコード)」の行に例外をスロー。だから私たちの仕事は次の通りです:

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; 
    } 
    ... 
} 

この第2のコードブロックは機能しますが、私はそれが理想的ではないと感じています。

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(); 
     } 
    } 
関連する問題