EF 4.1代码第一次 - 确定哪些属性已更改 [英] EF 4.1 Code First - Determine What Properties Have Changed

查看:205
本文介绍了EF 4.1代码第一次 - 确定哪些属性已更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架4.1代码第一。是否有一个内置的方式得到一个什么样性质已经改变,因为实体已经从数据库加载列表?我知道代码首先检测到某个对象改变了,但有一种方式来获得什么性质已经改变?

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?

推荐答案

有关标量和复杂的属性,你可以使用以下方法来提取实体 myEntity所的更改的属性名称:

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 仅包含标量和复杂性,没有导航属性。

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



......那么,如果 myEntity所 CurrentValues.PropertyNames 将包含编号 命名地址而不是 Address.Country Address.City (也不是的国家城市)。

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

如果一个复杂的属性被修改后标记( .IsModified 在上面的代码是真正),那么这意味着,无论是引用( Person.Address 在上面的例子中)发生了变化,不管实际的属性值(国家城市)的复杂类型的内部已经改变与否。或者说,任何复杂类型的属性已经改变(国家城市已经改变)。我认为这是不可能找出哪一个,因为EF总是发出一个UPDATE命令的所有的复杂类型的属性到数据库中,即使只有一个属性发生了变化,其他保持不变。我想从这个结论是EF不跟踪单个复杂类型的属性变化。

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.

这篇关于EF 4.1代码第一次 - 确定哪些属性已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆