Why use Attach for update Entity Framework 6?

那年仲夏 提交于 2019-12-03 11:54:31
octavioccl

If you have an entity that you know already exists in the database but which is not currently being tracked by the context - which is true in your case - then you can tell the context to track the entity using the Attach method on DbSet. So in summary what Attach method does is track the entity in the context and change its state to Unchanged. When you modify a property after that, the tracking changes will change its state to Modified for you. In the case you expose above you are telling explicitly that state is Modified but also to attach the entity to your context. You can find a detailed explanation in this post.

When should you use Attach method?

When you have an entity that you know already exists in the database but want to make some changes:

var entity= new Entity{id=1};
context.YourDbSet.Attach(entity); 

// Do some change...  
entity.value=5;

context.SaveChanges(); 

This is the same:

 context.Entry(entity).State = EntityState.Unchanged; 

// Do some change... 
entity.value=5; 

context.SaveChanges(); 

When should you change entity's State to Modified explicitly?

When you have an entity that you know already exists in the database but the changes have already been made then. The same scenario of your example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!