1

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()?

Milos Mrdovic
  • 1,441
  • 1
  • 17
  • 30
  • 1
    That's why [foreign key associations](http://stackoverflow.com/q/5281974/861716) are so useful: you can set a primitive property. – Gert Arnold Apr 05 '13 at 13:23
  • Thanks for the hint. But using fka requires modifying my model to include Address' foreign keys which means tighter coupling with the database and introducing relational concept to the object model... Doesn't this defy the very purpose of ORMs? – Milos Mrdovic Apr 05 '13 at 19:52
  • 1
    ORMs always leave a footprint in the domain. If you use them do it in a the way that suits them best, which, in case of EF, is with FKAs. – Gert Arnold Apr 05 '13 at 21:11

0 Answers0