I am trying to attach an Entity that has never been ‘pulled’ from the DB and have it update the existing row. For example, I am passing a full model through in MVC (modified), and I am just trying to save it without a roundtrip to first get the entity, then edit since I already have the info from a previous call.
What I have is this:
public static int ModifyExistingEntity<T>(this DbContext db, T updated) where T : class
{
DbSet<T> set = db.Set<T>();
set.Attach(updated);
db.Entry(updated).State = EntityState.Modified;
return db.SaveChanges();
}
But when I run it I get this:
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store
update, insert, or delete statement affected an unexpected number of
rows (0). Entities may have been modified or deleted since entities
were loaded. Refresh ObjectStateManager entries. —>
System.Data.OptimisticConcurrencyException: Store update, insert, or
delete statement affected an unexpected number of rows (0). Entities
may have been modified or deleted since entities were loaded. Refresh
ObjectStateManager entries.
Which means nothing was updated. What am I missing here? The primary Key is set correctly, but remember that the Entity is not pulled from the DB, it was constructed from previously queried information + updates.
May be some issue with the static extension you can try with inheritance,