4

I have an entity retrieved from db as follows

using ( var ctx = new Mycontext() )
   return ctx.MyGroups.First( // query );

this is bound to UI and updated on user save action as follows

using ( var ctx = new Mycontext() )
{
    ctx.MyGroups.Attach(o); // verified object o is updated 
    ctx.SaveChanges();

}

However the db is NOT updated

Environment is .net 4.0, db is sql compact 4

Any help on what could be missing/wrong ?

4

3 回答 3

11

当您将对象附加到上下文时,它们的默认状态是未更改,您应该通过设置强制更新DBContext.Entry(entity).State = EntityState.Modified;并且仅在该调用之后DBContext.SaveChanges();

于 2012-04-30T08:49:20.100 回答
0

正如Ciobanu Ion所建议的,这是您的解决方案:

using ( var ctx = new Mycontext() ) 
{ 
    ctx.MyGroups.Attach(o); // verified object o is updated  
    ctx.ObjectStateManager.ChangeObjectState(o, EntityState.Modified);
    ctx.SaveChanges(); 

} 

编辑从 EF 6 开始,上述解决方案不起作用。相反,请使用以下内容:

using ( var ctx = new Mycontext() )
{
    ctx.MyGroups.Attach(o); // verified object o is updated 
    ctx.Entry(entity).State = EntityState.Modified;
    ctx.SaveChanges();
}
于 2012-04-30T08:58:58.357 回答
0

Attach方法依赖于主键将实体附加到对象上下文。在我看来,当您的对象从视图和模型绑定更改时,更新的对象中缺少主键值。

于 2012-04-30T05:34:59.230 回答