EF 4.1 Code First - Determine What Properties Have Changed

Dylan Vester picture Dylan Vester · Aug 18, 2011 · Viewed 7.7k times · Source

I'm using Entity Framework 4.1 Code First. Is there a built-in way to get a list of what properties have changed since the entity was loaded from the database? I know code first detects that an object was changed, but is there a way to get exactly what properties have changed?

Answer

Slauma picture Slauma · Aug 19, 2011

For scalar and complex properties you can use the following to extract the changed property names of an entity myEntity:

var entry = context.Entry(myEntity);
var namesOfChangedProperties = entry.CurrentValues.PropertyNames
    .Where(p => entry.Property(p).IsModified);

A few things to note here:

  • CurrentValues.PropertyNames only contains scalar and complex properties, not navigation properties.

  • Complex properties means: Only the name of the complex property which is declared on the entity, not the actual individual properties of the complex type itself, for example: If you have this model...

    [ComplexType]
    public class Address
    {
        public string Country { get; set; }
        public string City { get; set; }
    }
    
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Address Address { get; set; }
    }
    

    ... then, if myEntity is a Person, CurrentValues.PropertyNames would contain "Id", "Name" and "Address" but not "Address.Country" or "Address.City" (nor "Country" or "City").

  • If a complex property is marked as modified (.IsModified in the code above is true) then this means that either the reference (Person.Address in the example above) has changed, no matter if actually the property values (Country and City) inside of the complex type have changed or not. Or that any of the properties of the complex type has changed (Country or City has changed). I believe it's not possible to find out which one, because EF always sends an UPDATE command for all complex type properties to the database, even if only one property has changed and the other remained unchanged. I would conclude from this that EF doesn't track changes of individual complex type properties.