简体   繁体   中英

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

I am updating a list of objects from a web page:

Entity

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

        public int parentID { get; set; }

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

CRUD Operation:

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

}

What is the proper way to add the new items, Update the existing items and Remove the items that have been removed on the screen? This seems terribly inefficent and I am convinced there is a better way.

First of if u use virtual, it will be very slow, I would recommend you use eager loading rather than lazy loading.

When you are updating the Parents, you don't have to load children if you are not updating Children.

If you need to load the children as well, you can get all of them at once, rather than one by one, which is more efficient as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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