2015-03-31 63 views
0

我从一个网页更新的对象的列表:在EF 6中处理CRUD操作的正确方法在处理集合时?

实体

public partial class MyParentType 
    { 
     public MyParentType() 
     { 
      this.children = new HashSet<child>(); 
     } 

     public int parentID { get; set; } 

     public virtual ICollection<child> children { get; set; } 
    } 

CRUD操作:

public class MyRepository : IMyRepository 
    { 
     private readonly IErrorLogger _logger; 
     private readonly CorporateEntities _context; 

     public MyRepository(IErrorLogger logger) 
     { 
      _logger = logger; 
      _context = new CorporateEntities(); 
     } 

     public void Update(IEnumerable<MyParentType> parents) 
{ 
    try 
    { 
     foreach (var parent in parents) 
     { 
     if(parent.Id==0) 
     { 
      _context.MyParentTypes.Add(parent); 
     } 
     else 
     { 
      _context.Entry(parent).State = EntityState.Modified; 
      var removedChildren = 
          _context.Children.Where(
           x => !fuelProcessing.Children.Select(
            y => y.ID).Contains(x.ID)); 
      _context.Children.RemoveRange(removedChildren); 

      foreach(var child in parent.children) 
      { 
       context.Entry(child).State =child.Id>0? EntityState.Modified:EntityState.Added; 
      } 
     } 
     } 

     _context.SaveChanges(); 
    } 
    catch (Exception exception) 
    { 
    _logger.Error(exception.Message, exception); 
    } 
    } 

} 

什么是正确的方式来添加新项目,更新现有的项目并删除已在屏幕上删除的项目?这看起来非常麻烦,我相信还有更好的办法。

回答

0

首先,如果你使用虚拟,它会很慢,我会建议你使用急切加载而不是延迟加载。

当您更新父母时,如果您没有更新孩子,则不必加载孩子。

如果您还需要加载子项,您可以一次性获得所有项目,而不是逐个项目,效率更高。

+0

我确实需要每次更新孩子。你能给出一个模板化的例子吗? – Robert 2015-03-31 16:11:58

+0

如果你需要更新孩子,你可以一次加载它们。看看急切的加载。 – DarthVader 2015-03-31 16:18:37