实体框架6 - 无法更新表中的单个列

时间:2015-04-17 11:59:32

标签: entity-framework

我有以下方法尝试更新数据库表中的单个列(而不是对象的整个图!):(运费):

    public void UpdateShippingCost(Entities.ShoppingCart shoppingCart)
    {
        // Map from domain entity to database object
        var shoppingCartRecord = Mapper.Map<ShoppingCart>(shoppingCart);

        shoppingCartRecord.ShippingCost = 99.99M;

        dbContext.ShoppingCart.Add(shoppingCartRecord);

        var entry = dbContext.Entry(shoppingCartRecord);
        entry.Property(e => e.ShippingCost).IsModified = true;
        dbContext.SaveChanges();
    }

执行entry.Property(e => e.ShippingCost).IsModified = true;行时,出现以下错误:

Additional information: SetModifiedProperty cannot be called because the object is not in a modified or unchanged state.

这怎么可能?我当然修改了这个对象。

1 个答案:

答案 0 :(得分:4)

致电DBSet<>.Add()会将实体标记为Added。因此,将特定属性标记为Modified没有任何意义。

要更新现有实体,请致电DbContext.Attach()向EF开始跟踪实体,而不是DbSet<>.Add()