【发布时间】:2012-04-09 08:10:11
【问题描述】:
假设我们有 Customers 和 CustomerCategories 具有 n-n 关系 DbContext/ObjectContext。我也想维护AuditLog 表中的关系状态。在常规情况下,我可以通过以下代码达到此目的:
通过以下代码获取ChangeTracker 中的关系状态:
foreach (ObjectStateEntry dbEntry in){
objectContext
.ObjectStateManager
.GetObjectStateEntries(~EntityState.Detached)
.Where(o=>o.IsRelationship)
然后通过以下代码找到两个相关实体的键:
(dbEntry.CurrentValues.GetValue(0) as EntityKey).EntityKeyValues[0].Value //for the key of related entity in customers table
(dbEntry.CurrentValues.GetValue(1) as EntityKey).EntityKeyValues[0].Value //for the key of related entity in CustomerCategories table
除非新添加的相关客户或相关客户类别导致上述代码返回 null,否则一切正常。所以我找不到相关实体。
有没有办法正确找到相关实体?
【问题讨论】:
标签: entity-framework entity-framework-4.1 change-tracking