2011-08-15 28 views
1

我正在使用Code First Entity Framework 4.1。我使用的两个实体是“国家”和“用户”。每个州的条目都有一个“CreatedBy”用户和“ModifiedBy”用户属性,如下所示。使用相同的密钥附加分离的条目

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

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

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

回答

0

一个解决办法是检查是否使用相同的密钥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 

好了,我不会,虽然称这是一个“简单的解决方案”。但我不知道另一个。如果您的外键属性CreatedByIdModifiedById位于State,它将变得更容易。您只需将导航属性CreatedByModifiedBy设置为null,并仅将外键属性设置为相关用户的ID。

相关问题