EF 4.1 Code First - 确定更改了哪些属性
我正在使用 Entity Framework 4.1 Code First。是否有一种内置方法可以获取自数据库加载实体以来已更改的属性的列表?我知道代码首先检测到对象已更改,但是有没有办法准确获取已更改的属性?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于标量和复杂属性,您可以使用以下方法提取实体
myEntity
已更改的属性名称:这里需要注意的一些事项:
CurrentValues.PropertyNames
仅包含标量和复杂属性,而不是导航属性。复杂属性意味着:仅在实体上声明的复杂属性的名称,而不是复杂类型本身的实际单个属性,例如:如果您有此模型...
<前><代码>[复杂类型]
公开课地址
{
公共字符串国家{获取;放; }
公共字符串城市{获取;放; }
}
公开课人物
{
公共 int Id { 得到;放; }
公共字符串名称{获取;放; }
公共地址地址 { get;放; }
}
...那么,如果
myEntity
是Person
,CurrentValues.PropertyNames
将包含“Id” 、“名称”和“地址”,但不是“地址.国家/地区”或“地址.城市”(也不是“国家”或“City”)。如果复杂属性被标记为已修改(上面代码中的
.IsModified
为true
),则这意味着引用 (Person.Address<上例中的 /code> 已更改,无论复杂类型内部的属性值(
Country
和City
)实际上是否已更改。或者复杂类型的任何属性已更改(Country
或City
已更改)。我相信不可能找出哪一个,因为 EF 总是向数据库发送所有复杂类型属性的 UPDATE 命令,即使只有一个属性发生了变化而另一个属性保持不变。我由此得出的结论是,EF 不会跟踪单个复杂类型属性的更改。For scalar and complex properties you can use the following to extract the changed property names of an entity
myEntity
: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...
... then, if
myEntity
is aPerson
,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 istrue
) then this means that either the reference (Person.Address
in the example above) has changed, no matter if actually the property values (Country
andCity
) inside of the complex type have changed or not. Or that any of the properties of the complex type has changed (Country
orCity
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.