实体框架更改跟踪 API 和参考条目
希望在我的 DbContext 子类上编写通用审核代码。
foreach (var entry in this.ChangeTracker.Entries<MyClass>())
{
if (entry.State == EntityState.Modified)
{
var entityProperties = entry.Entity.GetType().GetProperties();
foreach (var entityProperty in entityProperties)
{
DbMemberEntry propertyEntry = entry.Member(property.Name);
if (propertyEntry is DbPropertyEntry)
{
// IsModified available
}
else if (propertyEntry is DbReferenceEntry)
{
// IsModified not available
}
}
}
}
1)如果我只更改引用属性,则entry.State值为“未更改”。
2) 即使第 1 点设置为“Modified”,DbReferenceEntry 类似乎没有 IsModified 属性,也没有原始值。
我认为这是可能的,因为 EF 必须跟踪这一点。
有人可以帮忙吗?
谢谢, 本
Looking to write generic Audit code on my DbContext subclass.
foreach (var entry in this.ChangeTracker.Entries<MyClass>())
{
if (entry.State == EntityState.Modified)
{
var entityProperties = entry.Entity.GetType().GetProperties();
foreach (var entityProperty in entityProperties)
{
DbMemberEntry propertyEntry = entry.Member(property.Name);
if (propertyEntry is DbPropertyEntry)
{
// IsModified available
}
else if (propertyEntry is DbReferenceEntry)
{
// IsModified not available
}
}
}
}
1) If I only change a reference property, the entry.State value is "Unchanged".
2) Even if point 1 was set to "Modified", the DbReferenceEntry class doesn't seem to have an IsModified property, nor an original value.
I assume this is possible because EF must be tracking this.
Can anyone help?
Thanks,
Ben
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,参考条目(导航属性)不跟踪更改。它是外键属性(在外键关联的情况下)或独立关联的单独对象跟踪更改的责任。在 ObjectContext API 中,您可以通过 ObjectStateManager 获取这些对象,但看起来 DbContext API 没有此功能。我在 MSDN 论坛。
Yes reference entry (navigation property) does not track changes. It is responsibility of foreign key property (in case of foreign key association) or separate object tracking changes of independent association. In ObjectContext API you can get these objects by
ObjectStateManager
but it looks like DbContext API doesn't have this available. I asked a question about this on MSDN Forum.