EF Update Using EntityState.Modified

I usually use this code

Member member = ctx.Members.Find(id); member.Name = txtName.Text; ctx.Entry(member).State = EntityState.Modified; ctx.SaveChanges(); 

when I want to update the model using the framework entity. I found an example of https://stackoverflow.com/a/166149/ which does not use EntityState.Modified to update the model. I am trying to delete a row and it still works. What are the pros and cons of using EntityState.Modified and not using EntityState.Modified ?

Notes: I am using Entity Framework 6 Code First in WinForms

+6
source share
3 answers

EntityState.Modified is useless in your case because the object you are updating is already being tracked by the context when you retrieve it from the context.

You will need this in the following scenario, in which you are not extracting your entity from the context:

 Member member = new Member({Id=1, Name="member"}) ; context.Entry(member).State = EntityState.Modified; context.SaveChanges(); 

In addition, as indicated in the previous answer, your context sometimes only tracks a limited “view” of the database, and therefore you need to start tracking manually, as shown above.

Microsoft doc

+10
source

Like other guys, your context tracks object changes automatically.

I find it more useful, for example, when I use return json for the mvc controller, where the original object loses change tracking when it is first converted to json for presentation. In this case, before saving the changes, I must specifically set the state of the object of the objects.

+4
source

If you use change tracking, then proxy objects automatically listen for property changes and the update context, which is very useful in mvvm, where you simply bind properties to controls and do not have to write code to update the context.

If you do not use change tracking (for example, when you are dealing with a large number of entities), you must update the context yourself

+2
source

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


All Articles