I am currently working on a project using the latest version of Entity Framework and I have come across an issue which I can not seem to solve.
When it comes to updating existing objects, I can fairly easily update the object properties ok, until it comes to a property which is a reference to another class.
In the below example I have a class called Foo, which stores various properties, with 2 of these being 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 below Edit()
method, I pass in the object I wish to update and I can manage to get the Name
to properly update, however I have not managed to find a way in which to get the properties of the SubFoo to change. For example, if the SubFoo
class has a property of Name
, and this has been changed and is different between my DB and the newFoo
, it does not get 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 the comment by Slauma I have modified 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 running this now, I get the error:
The entity type Collection`1 is not part of the model for the current
context.
To try and get around this, I added code to try to attach the newFoo
subclasses to the context, but this through an error saying that the ObjectManager
already had an entity the same:
An object with the same key already exists in the ObjectStateManager.
The ObjectStateManager cannot track multiple objects with the same
key
See Question&Answers more detail:
os