locked
Why does the EntityFramework update the master entity in a master-detail relationship if a detail entity is modified? RRS feed

  • Question

  • I have a very simple master-detail structure in database which is accessed via Entity Framework using the following model:

    Entity Framework model
    Master entity modifications are mapped via Insert/Update/Delete stored procedures.

    A Detail entity is loaded and edited and it's Master entity is loaded into the context as well but that is not modified. When changes are saved both Detail and Master entities are updated even though the Master entity was not changed at all (Detail entity => parameterized update statement; Master entity => update stored procedure call).

    using (var context = new PlayGroundEntities()) 
    { 
       
    var master = context.Masters.First(m => m.MasterId == MasterAId); 
       
    var detail = context.Details.First(d => d.DetailId == MasterADetail1Id); 
        detail
    .DetailValue = "Detail Value"; 
        context
    .SaveChanges(); 
    } 

    This is very strange for me and I would like to get rid of the Master entity update sp call if the Master entity is not modified. If Master entity updates are not mapped via stored procedures (normal ef stuff, simple parameterized insert/update/delete sql statements are generated) this strange behavior does not occur.

    This is just a very simple example. In the real project I have a complex model where the same problem occurs and I would like really much to get rid of that. Unfortunately I really have to use the stored procedure mappings and the loading of the "Master" entity is also important.

    Did anybody experience something like this or managed to get rid of it somehow? I am using Entity Framework 4.0 released with .NET Framweork 4.0.

    Thank You in advance for Your help!

    Please note that this question was asked also on StackOverflow
    You may want to follow comments/answers there as well: http://stackoverflow.com/questions/8136650/why-does-the-entityframework-update-the-master-entity-in-a-master-detail-relatio

    Wednesday, November 16, 2011 9:07 AM

Answers

  • Hi hadadiz,

    Welcome!

    I can repro your scenario, When I update the detail's properties, the "Master" 's state is still "Unchanged", but the update stored procedure ran. Based on my understanding, we can detach the Master instance before SaveChanges, I tested it and it works as expected:

    db.ObjectStateManager.GetObjectStateEntry(master).ChangeState(System.Data.EntityState.Detached);

    Have a nice day.

     


    Alan Chen[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by Alan_chen Monday, November 28, 2011 3:47 AM
    Thursday, November 17, 2011 8:01 AM