Entity Framework Save changes on Collection

c# entity-framework-6

Question

I have this piece of code

public int Update(Item item)
{
    using (var ctx = new DataConext())
    {
        ctx.Entry(item).State = EntityState.Modified;
        return ctx.SaveChanges();
    }
}

Class Item
{
 public string Name {get;set;}
 public ICollection<Foobar> Foos {get;set;}
}

Class Foobar
{
 public string FirstName {get;set;}
 public string LastName {get;set;}
}

Lets say:

item.Foos.ElementAt(0).FirstName = "edited name"

SaveChanged() is executed but I have the 'old' values on the database and not 'edited name'...

I can see the correct changes in Local in debug.

1
0
1/11/2016 8:26:00 PM

Accepted Answer

Looks like your object came from a different context that the one you are using now. In that case you can't do that with a generic because you need to do a foreEach in your Foobar collection and change the state for each item individually.

What you have here is a disconnected entity graph so the entity is disconnected and change tracking is lost. You only set the state of the main entity and so EF assumes that everything else is unchanged.

Jullie Lerman's books is a good source to understand how this works

What I would do is I would keep this method for simple entities but make it virtual so you can inherit this repo to create specific entity repos and override the update method with a more specific implementation suitable to an entity like the one in your example.

An article that helped my to design such a repo was this: http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application.

2
3/28/2017 1:13:05 PM

Popular Answer

Class Item
{
    public string Name {get;set;}
    public ICollection<Foobar> Foos {get;set;}
}

You need Include to include the Foos to the object manager. Right now, it is eager loading. Whereever youare loading the item, you have to include it.

You should use include.

Or you can use virtual to have them lazy load.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow