I am currently working on a project using the latest version of the Entity Framework, and I ran into a problem that I seem to be unable to solve.
When it comes to updating existing objects, I can pretty easily update the properties of the ok object until I get to a property that is a reference to another class.
In the example below, I have a class Foo that stores various properties, and 2 of them are instances of other classes
public class Foo { public int Id {get; set;} public string Name {get; set;} public SubFoo SubFoo {get; set} public AnotherSubFoo AnotherSubFoo {get; set} }
When I use the Edit() method below, I go through the object I would like to update, and I can manage to get the Name to update correctly, however I could not find a way in which to get the SubFoo property into change. For example, if the SubFoo class has a Name property, and it has been changed and differs from my DB and newFoo , it is not updated.
public Foo Edit(Foo newFoo) { var dbFoo = context.Foo .Include(x => x.SubFoo) .Include(x => x.AnotherSubFoo) .Single(c => c.Id == newFoo.Id); var entry = context.Entry<Foo>(dbFoo); entry.OriginalValues.SetValues(dbFoo); entry.CurrentValues.SetValues(newFoo); context.SaveChanges(); return newFoo; }
Any help or pointers would be greatly appreciated.
UPDATE: Based on Slauma's comment, I changed my method to
public Foo Edit(Foo newFoo) { var dbFoo = context.Foo .Include(x => x.SubFoo) .Include(x => x.AnotherSubFoo) .Single(c => c.Id == newFoo.Id); context.Entry(dbFoo).CurrentValues.SetValues(newFoo); context.Entry(dbFoo.SubFoo).CurrentValues.SetValues(newFoo.SubFoo); context.SaveChanges(); return newFoo; }
When you run this now, I get an error message:
The object type Collection'1 is not part of the model for the current context.
To try to get around this, I added code to try to subclass newFoo in the context, but this is with an error saying that the ObjectManager already had an entity:
An object with the same key already exists in the ObjectStateManager. ObjectStateManager cannot track multiple objects with the same key