R – How to determine if an Entity with relationship properties has changes

entity-framework

Dim myEmployee as Employee = myObjectContext.Employee.Where("it.EmployeeID = 1").First()

The following line will cause e.EntityState to equal EntityState.Modified :

myEmployee.Name = "John"

However, changing a property that is a relationship will leave e.EntityState = EntityState.Unchanged. For example:

myEmployee.Department = myObjectContext.Department.Where("it.DepartmentName = 'Accounting'").First()

How can I tell if myEmployee has changes? I need to know so I can log changes made to the Employee record for auditing purposes.

Best Answer

There is a way to get the state of a relationship, but it is not as easy to obtain as the state of an entity.

ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState state) returns IEnumerable<ObjectStateEntry> with entries for both, entities and relationships (there is IsRelationship property on ObjectStateEntry so you can determinate if it's relationship or entity).

I tested out with with your example when relationship is changed the way you do

myEmployee.Department = myObjectContext.Department.Where("it.DepartmentName = 'Accounting'").First()

and I find out by calling GetObjectStateEntries for each possible EntityState that one ObjectStateEntry is added with state Added:

myObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added)

Now, you can peek at the current values of the state entry to see if they match the ends of the relationship (not nice). However, it's a bit complicated and I'm not sure if it's going to meet your needs in every case.

Related Topic