实体框架:带子项的附加对象

时间:2014-06-18 21:29:54

标签: c# entity-framework

如本topic中所述,如果您想插入或更新实体,可以使用以下方法:

if (myEntity.Id != 0)
{
    context.MyEntities.Attach(myEntity);
    context.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
    context.MyEntities.AddObject(myEntity);
}

context.SaveChanges();

问题是在我的情况下myEntity有一些与子相关的对象,因此当我尝试更新它时(myEntity.Id!= 0)我收到以下异常:

System.InvalidOperationException was unhandled
Message=An object with a temporary EntityKey value cannot be attached to an object context.

如果我从myEntity删除子对象(注释掉),一切正常..

有人知道如何解决这个问题吗?如何更新myEntity并将其与子对象一起保存?谢谢!

编辑:

这是问题的解决方案:stackoverflow.com/a/7969372/282649

0 个答案:

没有答案