【问题标题】:DbContext ChangeTracker issue with relationshipsDbContext ChangeTracker 关系问题
【发布时间】:2012-04-09 08:10:11
【问题描述】:

假设我们有 CustomersCustomerCategories 具有 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


    【解决方案1】:

    最后,几个小时后,我找到了一个简单的解决方案:GetObjectByKey ObjectContext 有而 DbContext 没有的方法!它通过实体引用搜索整个上下文。所以我做了它而不是上面的代码:

     objectContext.GetObjectByKey((dbEntry.CurrentValues.GetValue(0) as EntityKey));
     objectContext.GetObjectByKey((dbEntry.CurrentValues.GetValue(1) as EntityKey));
    

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2013-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多