Adding and updating entities with Entity Framework

后端 未结 2 1379
栀梦
栀梦 2021-02-04 15:00

In my last project I have used Entity Framework 5 Code First. I completed my project but had a lot of pain during the development process.

I tried to explain my pain bel

2条回答
  •  半阙折子戏
    2021-02-04 15:39

    You can replace your code by:

    context.Products.Attach(entity);
    context.Entry(entity).State = System.Data.EntityState.Modified;
    

    The reason why this is the same (unless the related entities were already attached to the context in another state than Unchanged before) is that Attach puts entity including all related entities in the object graph into the context in state Unchanged. Setting the state to Modified afterwards for entity only changes the state of the product alone (not the related entities) from Unchanged to Modified.

提交回复
热议问题