异常:无法附加对象

时间:2013-11-17 03:36:02

标签: entity-framework c#-4.0

我试图通过循环共享表的所有记录并更新每行的价格来使用实体框架:

public static void UpdateSharesPrices()
{
    foreach (var share in db.shares)
    {
        share.price=10;
        db.shares.Attach(share);
        db.ObjectStateManager.ChangeObjectState(share, EntityState.Modified);
        db.SaveChanges();
    }
}

db.shares.Attach ..虽然给我一个错误?

The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state.

如何做到这一点或解决这个问题?

1 个答案:

答案 0 :(得分:0)

在我看来,你在努力尝试。根据我的经验,这就是你所需要的。

public static void UpdateSharesPrices()
{
    foreach (var share in db.shares)
    {
        share.price=10;
    }
    db.SaveChanges();
}