Based on an EF Code First tutorial by Julie Lerman (http://msdn.microsoft.com/en-us/data/gg715119), I am using something similar to the following code snippet to update my model in an MVC 4 application:
public ActionResult Edit(int id, Person person)
{
using (var db = new MyDbContext())
{
person.Address = db.Addresses.Find(312);
db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
}
}
This saves all the scalar properties of my Person object, but not the reference to the new Address. While debugging, I can see that my DbContext is aware of the updated person. After calling SaveChanges(), the ChangeTracker has the new person with the correct Address and State == Unchanged. However, next time I look at the database, I see the old Address instead of the new one...
Am I doing something wrong? Is this behavior by design?
Thanks in advance!
Clarification:
This question is inspired by the behavior of some of the pure object databases (such as db4o and others) and it is about the inner workings of the DbContext API (or EF in general).
By slightly changing the statements to this:
using (var db = new MyDbContext())
{
var p = db.Person.Find(person.Id);
// Variable p is now a person's proxy...
db.Entry(p).CurrentValues.SetValues(person);
// The above statement seems unnecessary, but it is actually required...
p.Address = db.Addresses.Find(312);
db.SaveChanges();
}
everything is saved, as expected.
What puzzles me is why do we have to use foreign key associations in our model, as Mr. Arnold suggested, just to be able to use previous (simple) syntax to update both object's references as well as its scalar properties? After calling db.Entry(person), where the person has all the correct references to other objects, why is the EF completely ignoring them (in contrast to many object databases) and just updates its scalars on a call to SaveChanges()?