What do I have to do to have Entity Framework immediately sync the foreign key and the navigation property whenever either is changed, not just after calling SaveChanges
?
public class Model
{
[Key]
public int ModelId { get; set; }
public string Name { get; set; }
public virtual Model Other { get; set; }
[ForeignKey("Other")]
public int OtherId { get; set; }
// Other regular mapped properties not shown
}
I'm using EF 6.1.3 Code First. Change tracking is not explicitly deactivated and should be used.
I need this because my UI grid control changes the ID only (changing navigation object here causes trouble) but my business logic requires information from the referenced object immediately after the ID was changed, before saving the record. The referenced object's data determines what other options the user has to edit the record.
It seems that this question answers my question:
All mapped properties must be virtual. As soon as a single mapped property is not virtual, the whole thing doesn't work anymore and nobody tells you.
I haven't seen an easy way to verify that this is done, but if it is done, Entity Framework will apply some "More efficient change tracking" which also has the effect of foreign key properties updating navigation properties, and vice versa.
Oh, and this only works with Entity Framework proxy classes. You get these when querying existing objects, or with the
DbSet.Create()
method. Creating new instances of the model class directly won't do anything automatically.