Email Q&A: Entity Framework Modified State and SaveChanges

I get a lot of Entity Framework questions in email. Some from friends, some from people I don’t know. I like to help & answer when I can but this format means that nobody else gets to learn from the question. That’s one of the benefits of asking (or first researching) on the forums, stackoverflow.com and other community forums are so great…others can learn from your questions. Or you can learn from theirs!

Here is one of the 10 or so questions I got over the weekend. I was happy to answer because it was an easy one for me. (They aren’t all so easy for me… Winking smile)

The developers was hitting a very common point of confusion about setting Entry.State with graphs.

Question:

Hi julia!

what am I missing…

I have code first entities:

MaritalStatus

{

int id {get;set}

string Description {get;set}

}

Person

{

int Id {get;set;}

string FirstName {get;set;}

string LastName {get;set;}

MaritalStatus MaritalStatus {get;set}

}

I am binding control DataContext to a selected person

I have text boxes bound to the name parts, I have a combo box bound to a list of marital status.

the bindings all work – I change the combo, I can see in the debugger that is putting the selected marital status on my bound object

I execute this code to save the person:

using (var context = new PersonnelContext())

{

context.Entry(Person).State = System.Data.EntityState.Modified;

context.SaveChanges();

}

the name parts persist, but the marital status doesn’t.

Any ideas????

 

Answer:

Setting the State of an Entry to modified affects ONLY the object whose state you are setting. I t will have no affect whatsoever on other objects in the graph.

By passing Person into context.Entry, the full graph attached to Person will also get attached to the context. But initially, everything will be marked as Unchanged. Then the code changes the state of the Person object to Modified. The rest of the objects in that graph remain Unchanged.

SaveChanges will only send an UPDATE command to the database for the Person object.

 

Hope it helps.

P.S. This same information is in Chapter 4 of Programming Entity Framework: DbContext, starting on page 88.

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

2 thoughts on “Email Q&A: Entity Framework Modified State and SaveChanges

  1. Thanks for answering julia!!!

    Also for those looking at this and code first, refer to

    Chapter 4. Using Convention and Configuration for Relationships

    in

    Programming Entity Framework: Code First

    there is a great little blurb "It’s Just Easier with Foreign Key Properties"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.