Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Update using EntityState.Modified

Usually I'm using 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 entity framework. I found an example on SO that doesn't use EntityState.Modified to update the model. I try to remove the line and it's still working. What is the pros and cons use EntityState.Modified and doesn't use EntityState.Modified?

Notes: I'm using Entity Framework 6 Code First in WinForms

like image 654
Willy Avatar asked May 15 '15 05:05

Willy


People also ask

What does EntityState Modified do?

Updates are not sent to the database for entities in the Unchanged state. Added entities are inserted into the database and then become Unchanged when SaveChanges returns. Modified entities are updated in the database and then become Unchanged when SaveChanges returns.

How do I update my EF record?

We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we already have the entity with use. Hence all we need to is to attach/add it to the context.

How do I change the state of entity using DB context?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.

How do I update my Entity Framework model in .NET core?

Right-click anywhere on the design surface, and select Update Model from Database... In the Update Wizard, select the Refresh tab and select your table then click Finish button.


2 Answers

The EntityState.Modified is useless in your case because the entity your are updating is already tracked by the context as you retrieve it from the context.

You would need it in the following scenario where you don't retrieve your entity from the context :

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

Also, as specified in previous answer, your context sometimes tracks only a limited "view" of the database and therefore you need to init the tracking manually like above.

Microsoft doc

like image 150
Yooz Avatar answered Sep 16 '22 11:09

Yooz


Like the other guys have mentioned your context tracks the changes to the object automatically.

I find it more useful for instance when I use return json to a mvc controller where the original object loses change tracking when first converted to json for the view. In that case I have to specifically set the objects entity state before saving changes.

like image 29
paulpitchford Avatar answered Sep 16 '22 11:09

paulpitchford