Randy Minder
Randy Minder

Reputation: 48402

Entity Framework 6 - Unable to update a single column in a table

I have the following method which is trying to update a single column (not the entire graph of the object!) in the database table (shipping cost):

    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();
    }

When the entry.Property(e => e.ShippingCost).IsModified = true;line is executed, I get the following error:

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

How can this be? I've certainly modified the object.

Upvotes: 1

Views: 847

Answers (1)

Andr&#233; Werlang
Andr&#233; Werlang

Reputation: 5944

A call to DBSet<>.Add() will mark the entity as Added. So there's no sense in marking a specific property as Modified.

In order to update an existing entity, call DbContext.Attach() to EF start tracking the entity, instead of DbSet<>.Add().

Upvotes: 4

Related Questions