Entity Framework Save changes on Collection

c# entity-framework-6

Question

I possess this program 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;}
}

Say this:

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

Although SaveChanged() is called, the database still contains the "old" values rather than the "updated name."

In debug, I can see the proper modifications in Local.

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

Accepted Answer

It appears that the context in which your object was used before the one you are using now is different. In that scenario, using a generic won't work because you'll need to perform a forEach on each item in your Foobar collection to modify the state of each item separately.

This situation results in a disconnected entity graph, which makes it impossible to track changes to the entity. EF expects that everything else remains constant because you just modified the state of the primary entity.

Books by Jullie Lerman are a fantastic resource for learning how this operates.

To construct particular entity repos, you can inherit this repository and override the update function with a more tailored implementation that is appropriate for an entity like the one in your example. I would keep this method for simple entities but make it virtual so you can do that.

This essay, 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, was helpful to me in designing such a repository.

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

Popular Answer

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

You mustInclude adding Foos to the object management It is currently eagerly loaded. You must include the object wherever you are loading it.

You must utilizeinclude .

You may also utilizevirtual to let them off the hook.



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