繁体   English   中英

处理集合时,在EF 6中处理CRUD操作的正确方法是什么?

[英]What is the proper way to handle CRUD Operations in EF 6 When dealing with Collections?

我正在从网页更新对象列表:

实体

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

}

添加新项目,更新现有项目和删除屏幕上已删除项目的正确方法是什么? 这似乎效率很低,我相信有更好的方法。

首先,如果您使用虚拟,它将非常慢,我建议您使用紧急加载而不是延迟加载。

更新父级时,如果不更新子级,则不必加载子级。

如果还需要加载子代,则可以一次获得所有子代,而不是一个接一个地加载,这样效率也更高。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM