使用相同的密钥附加分离的条目
我正在使用 Code First Entity Framework 4.1。我使用的两个实体是“状态”和“用户”。每个状态条目都有一个“CreatedBy”用户和“ModifiedBy”用户属性,如下所示。
public class State {
public virtual User CreatedBy { get; set; }
public virtual User ModifiedBy { get; set; }
}
User 实体没有任何对 State 实体的反向引用,即 State =>用户是“单向”的。
当存在具有相同“CreatedBy”和“ModifiedBy”用户属性的分离状态实体时,就会出现问题。当我尝试将状态实体附加到 dbContext 时,EntityFramework 抱怨 ObjectStateManager 发现了重复条目。我一直在寻找解决这个问题的简单方法。
I am using Code First Entity Framework 4.1. The two entities that I am using are "State" and "User". Each State entry has a "CreatedBy" User and "ModifiedBy" User properties as given below.
public class State {
public virtual User CreatedBy { get; set; }
public virtual User ModifiedBy { get; set; }
}
The User entity doesn't have any back reference to State entity, that is State => User is "Unidirectional".
The problem occurs when there is a detached State entity which has same "CreatedBy" and "ModifiedBy" User properties. When I try to attach State Entity to the dbContext, the EntityFramework complains that duplicate entry found by ObjectStateManager. I was looking for a simple solution for this issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种解决方案是检查具有相同密钥的
User
是否已在上下文中,如果是,则替换State
User 引用> 实体由附加到上下文的对象组成。比如说,state
是要附加的新State
实体:嗯,不过,我不会将此称为“简单的解决方案”。但我不知道另一位。如果您在
State
中有外键属性CreatedById
和ModifiedById
,事情会变得更容易。您只需将导航属性CreatedBy
和ModifiedBy
设置为null
,并仅将外键属性设置为相关用户的 Id。One solution would be to check if a
User
with the same key is already in the context and if yes, replace the detachedUser
references in yourState
entity by the objects which are attached to the context. Say,state
is the newState
entity to attach:Well, I would not call this a "simple solution" though. But I don't know another one. If you had foreign key properties
CreatedById
andModifiedById
inState
it would become easier. You could just set the navigation propertiesCreatedBy
andModifiedBy
tonull
and only set the foreign key properties to the Ids of the related users.