实体关系对象更新
请你告诉我我哪里错了。我有以下代码:
public void UpdateClient(Client oClient)
{
foreach(Mitarbeiter item in oClient.Mitarbeiters)
{
if (item.MiID==0)
{
context.Mitarbeiters.AddObject(item);
}
else {
var key = context.CreateEntityKey("Mitarbeiters",item);
object original;
if (context.TryGetObjectByKey(key,out original))
{
context.ApplyCurrentValues(key.EntitySetName,item);
}
}
}
context.Clients.First(c => c.ClID == oClient.ClID);
context.Clients.ApplyCurrentValues(oClient);
context.SaveChanges();
} 我收到了
ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同键的多个对象。
当我向 Mitarbeiters 添加新对象时
Please can you tell me where I am wrong. I had a following code:
public void UpdateClient(Client oClient)
{
foreach(Mitarbeiter item in oClient.Mitarbeiters)
{
if (item.MiID==0)
{
context.Mitarbeiters.AddObject(item);
}
else {
var key = context.CreateEntityKey("Mitarbeiters",item);
object original;
if (context.TryGetObjectByKey(key,out original))
{
context.ApplyCurrentValues(key.EntitySetName,item);
}
}
}
context.Clients.First(c => c.ClID == oClient.ClID);
context.Clients.ApplyCurrentValues(oClient);
context.SaveChanges();
}
I received
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
when I add a new object to Mitarbeiters
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您的类
Mitarbeiter
具有指向Client
的导航属性,并且当您运行循环时该属性不为 null(因此item.Client != null
) 然后,通过将item
添加到 ObjectSet,您还可以将引用的Client
添加到处于状态Added
的上下文中。 (添加实体不仅会添加实体本身,还会添加上下文中尚未存在的所有引用实体。) Later (context.Clients.First(c => c.ClID == oClient.ClID);
)您第二次加载客户端,该客户端已经处于Added
状态的上下文中,这就是异常的原因。尝试在添加
item
之前将客户端加载到上下文中:只是猜测,我不确定这是否能解决您的问题。
Assuming that your class
Mitarbeiter
has a navigation property toClient
and it is not null when you run through the loop (soitem.Client != null
) then by addingitem
to the ObjectSet you also add the referencedClient
into the context in stateAdded
. (Adding an entity does not only add the entity itself but also all referenced entities which are not yet in the context.) Later (context.Clients.First(c => c.ClID == oClient.ClID);
) you load the client a second time which is already in the context inAdded
state which is the reason for the exception.Try to load the client into the context before you add
item
:Just a guess, I am not sure if this will solve your problem.