First, determine what properties have changed in EF 4.1.

c# change-tracking code-first entity-framework


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?

8/18/2011 9:23:53 PM

Accepted Answer

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...

    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.

5/13/2015 3:30:00 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow