1

I am trying to log changes to the database so that the user can see who changed what. I am using the DbEntityEntry to go through and log the DbPropertyEntity that have been modified. I am running into a problem when I want to log changes to a navigation property. I use the Reference() method to get reference to the navigation property, however unlike DbPropertyEntity, DbReferenceEntry does not have a OriginalValue only a CurrentValue attribute. How do you get the OriginalValue of a navigation property?

//Get the field that hold the id of the foreign key
var field = entry.Property(x => x.field);

//Check to see if the user changed the value
if (field.IsModified)
{
    //Get the reference property associated with the field
    var fieldRef = entry.Reference(x => x.fieldRef);

    //Log the id change
    Log(field.Name, field.CurrentValue, field.OriginalValue);

    //Can't get the OriginalValue
    Log(fieldRef.Name, fieldRef.CurrentValue, ???);
}
Stefan Bossbaly
  • 6,682
  • 9
  • 53
  • 82

1 Answers1

1

What exactly do you expect to log for the reference?

If you want to log changes in relation (= changes in foreign key) you should map the foreign key as separate property and it will be logged as normal field. If you don't map the foreign key you have an independent association. Support for independent associations in DbContext API is limited. The full support is only in ObjectContext API (you can use it from DbContext API) but it will still not solve your problem - independent association cannot be in modified state. It can be either in unchanged, added or deleted state. If you change the reference the old association is marked as deleted and new is added = there are two separate association objects tracked by the context.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I am not using the edmx tools, I just created a database and add fields and then updated my domain objects. I am logging the foreign key change. The problem is that the user will see this log key changes won't make sense (example TypeID changed from a value of 3 to 4), I need to log the change in the navigation property (example Type changed from a value of Student to Teacher). – Stefan Bossbaly Jul 11 '12 at 20:56