EF 4.1 Code First - Determine What Properties Have Changed

后端 未结 1 1836
我寻月下人不归
我寻月下人不归 2021-01-31 20:36

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 firs

1条回答
  •  抹茶落季
    2021-01-31 21:03

    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.

    0 讨论(0)
提交回复
热议问题