First, determine what properties have changed in EF 4.1.

c# change-tracking code-first entity-framework


Entity Framework 4.1 Code First is what I'm utilizing. Is it possible to retrieve a list of the attributes that have changed since the entity was imported from the database using built-in functionality? I am aware that a change to an object is initially detected by code, but is there a method to determine precisely which attributes have changed?

8/18/2011 9:23:53 PM

Accepted Answer

To extract the updated property names for an entity's scalar and complex properties, use the following method.myEntity :

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

Note a couple aspects in this case:

  • CurrentValues.PropertyNames has no navigation properties; just scalar and complex properties.

  • Complex properties refer to just the name of the complex property, not the constituent attributes of the complex type itself, as in the following examples: If you own this model, then

    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; }

    hence, ifmyEntity is aPerson , CurrentValues.PropertyNames would not have "Address.Country" or "Address.City," but would have "Id," "Name," and "Address" (nor "Country" or "City").

  • In the event that a complicated property is tagged as changed (.IsModified in the aforementioned codetrue If this is the case, then the reference (Person.Address in the aforementioned example) has changed, regardless of whether the actual property values (Country and City ) have altered or not inside the complicated kind. Or that any of the complicated type's characteristics have changed (Country or City has altered). Since EF always sends a UPDATE instruction for all complex type properties to the database, even if only one property has changed and the other has stayed untouched, I don't think it's possible to determine which one. This would lead me to believe that EF doesn't keep track of changes to certain complicated type characteristics.

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