Reattaching an entity graph and detecting collection changes

后端 未结 2 1628
醉酒成梦
醉酒成梦 2021-01-13 08:16

I\'m using entity framework code first and exposing the northwind database through a WCF REST HTTP interface.

I\'ve not exposed the OrderDetails table (order items)

相关标签:
2条回答
  • 2021-01-13 08:33

    This is common and complex issue and there is no magic which will do it for you. My solution (and the only one which works in all scenarios) was to load the Order again in your update method and manually merge changes:

    public override Order Update(Order entity)
    {
        // No attach of entity
    
        var attached = DataContext.Orders.Include(o => o.OrderDetails).SingleOrDefault(...);
        if (attached == null) ...
    
        // Merge changes from entity to attached - if you change any property
        // it will be marked as modified automatically
    
        foreach (var detail in attached.OrderDetails.ToList())
        {
            // ToList is necessary because you will remove details from the collection
    
            // if detail exists in entity check if it must be updated and set its state
    
            // if detail doesn't exists in entity remove if from collection - if it is \
            // aggregation (detail cannot exists without Order) you must also delete it 
            // from context to ensure it will be deleted from the database
        }
    
        foreach (var detail in entity.OrderDetails)
        {
            // if it doesn't exists in attached create new detail instance,
            // fill it from detail in entity and add it to attached entity - 
            //you must not use the same instance you got from the entity
        }
    
        DataContext.SaveChanges();
    
        return entity;
    }
    

    There can be also need to manually check timestamps if you use them.

    Alternative scenario is what you have described with 0 used for new details and negative ID for deleted details but that is logic which must be done on client. It also works only in some cases.

    0 讨论(0)
  • 2021-01-13 08:50

    I've recently been allowed to open source some work I did for my employer a while ago (with some changes of course). I actually wrote an extension method to solve this problem, you can get it at http://refactorthis.wordpress.com/2012/12/11/introducing-graphdiff-for-entity-framework-code-first-allowing-automated-updates-of-a-graph-of-detached-entities/

    Hope it helps!

    0 讨论(0)
提交回复
热议问题