【问题标题】:Attaching detached entries with same key使用相同的键附加分离的条目
【发布时间】:2011-08-15 07:15:44
【问题描述】:

我正在使用 Code First Entity Framework 4.1。我使用的两个实体是“状态”和“用户”。每个 State 条目都有一个“CreatedBy”用户和“ModifiedBy”用户属性,如下所示。

public class State {
    public virtual User CreatedBy { get; set; }
    public virtual User ModifiedBy { get; set; }
}

User 实体没有对 State 实体的任何反向引用,即 State => User 是“单向”的。

当存在具有相同“CreatedBy”和“ModifiedBy”用户属性的分离状态实体时会出现问题。当我尝试将状态实体附加到 dbContext 时,EntityFramework 抱怨 ObjectStateManager 找到了重复条目。我一直在为这个问题寻找一个简单的解决方案。

【问题讨论】:

    标签: entity-framework-4.1 ef-code-first code-first


    【解决方案1】:

    一种解决方案是检查具有相同键的User 是否已经在上下文中,如果是,则将State 实体中分离的User 引用替换为附加到上下文的对象。比如说,state 是要附加的新 State 实体:

    if (state.CreatedBy != null)
    {
        var attachedCreatedBy = context.ChangeTracker.Entries()
            .Where(e => e.Entity is User
                     && e.Cast<User>().Entity.Id == state.CreatedBy.Id)
            .Select(e => e.Entity)
            .SingleOrDefault();
    
        if (attachedCreatedBy != null)
            state.CreatedBy = attachedCreatedBy;
    }
    
    if (state.ModifiedBy != null)
    {
        var attachedModifiedBy = context.ChangeTracker.Entries()
            .Where(e => e.Entity is User
                     && e.Cast<User>().Entity.Id == state.ModifiedBy.Id)
            .Select(e => e.Entity)
            .SingleOrDefault();
    
        if (attachedModifiedBy != null)
            state.ModifiedBy = attachedModifiedBy;
    }
    
    context.States.Attach(state); // now it should not throw an exception anymore
    

    不过,我不会将其称为“简单解决方案”。但我不知道另一个。如果您在State 中有外键属性CreatedByIdModifiedById,它会变得更容易。您可以将导航属性CreatedByModifiedBy 设置为null,并且只将外键属性设置为相关用户的ID。

    【讨论】:

      猜你喜欢
      • 2022-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多