Why use Attach to upgrade Entity Framework 6?

When searching for best practices for performing CRUD operations through EF, I noticed that before updating an object, it is strongly recommended that you use the Attach() or Find() methods. It works well and, according to the EF documentation, these methods bring the entity into a context that is completely clear to me. But the following code confused me pretty much

 public void Update(object entity) { Record record = new Record() { id = 1, value = 5 }; using (SomeContext ctx = new SomeContext()) { ctx.Entry(record).State = EntityState.Modified; ctx.SaveChanges(); } } 

Suppose we have an entry with id = 1 in the database. Under this condition, the above code will update the record (set the value to 5). The question is why does it work? And why should I use Attach() ? As far as I understand, the record is in no way contextual. I have read the relevant chapters of this book and tutorial , but they use a two-query approach. I am also angry, but could not find the answer to my question. Help me with an explanation or some good materials, please.

+5
source share
1 answer

If you have an entity that, as you know, already exists in the database, but which is not currently tracked by the context, as is your case, then you can specify the context for tracking the object using the Attach method on DbSet . So, in short, what the Attach method does is keep track of the entity in context and change its state to Unchanged . When you change a property after this, the tracking changes will change their state to Modified for you. In the case where you expand above, you explicitly indicate that the state is Modified , but also attaches the entity to your context. A detailed explanation can be found in.

When should you use the Attach method?

If 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(); 

Same:

  context.Entry(entity).State = EntityState.Unchanged; // Do some change... entity.value=5; context.SaveChanges(); 

When should you explicitly change the state of an object to Modified?

If you have an entity that, as you know, already exists in the database, but the changes have already been made. Same scenario of your example

+12
source

Source: https://habr.com/ru/post/1260943/


All Articles