Reputation: 48402
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
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