none
EF : Best way to track child changes ? RRS feed

  • Question

  • Hello,

    I have  a Database First EF context.

    On a regular basis, I will be reading some external data, and then update the Child records of the parent table .

    Currently, i delete all the children then add the children from my external data.

                    foreach (var childvm in asset.Childs.ToList()) 
                        {
                            db.Childs.Remove(childvm);
                        }

    But most of the time , the children data will be the same or only slightly different.

    is there a  better design to merge the records , and save a lot of sql activity ?

    Thanks,Peter

    Thursday, May 14, 2015 10:30 PM

Answers

  • Hello Peter,

    >>is there a  better design to merge the records , and save a lot of sql activity ?

    It is by designed that every change for an entity would generate a sql statements as an update statement, in your case, it could have a lot of update statements.

    If you want to avoid these lots of statement, you might need to pay some memory as the price. As you mentions, most of the time , the children data will be the same or only slightly different, so you could load these records need to be updated into local and do a comparison in your application, if these two compared records are same, you could ignore it and check the next one, if find the one which needs to be updated, assign new values to the old entity or detach the old one and attach:

    using (DFDBEntities db = new DFDBEntities())
    
                {
    
                    db.Database.Log = Console.Write;
    
    
                    for (int i = 1; i <= 3; i++)
    
                    {
    
                        Order order = new Order() { OrderID = i, OrderName = "2" };
    
                        var findMatch = db.Order.Find(order.OrderID);
    
                        db.Entry(findMatch).State = EntityState.Detached;
    
                        db.Entry(order).State = EntityState.Modified;
    
                    }
    
    
                    db.SaveChanges();
    
                }
    

    It is not sure if it is best, however, this approach does not generate those update statement for records containing same data.

    Regards.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, May 15, 2015 2:36 AM
    Moderator