How to update record using Entity Framework 6?
Solution 1:
You're trying to update the record (which to me means "change a value on an existing record and save it back"). So you need to retrieve the object, make a change, and save it.
using (var db = new MyContextDB())
{
var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
if (result != null)
{
result.SomeValue = "Some new value";
db.SaveChanges();
}
}
Solution 2:
I have been reviewing the source code of Entity Framework and found a way to actually update an entity if you know the Key property:
public void Update<T>(T item) where T: Entity
{
// assume Entity base class have an Id property for all items
var entity = _collection.Find(item.Id);
if (entity == null)
{
return;
}
_context.Entry(entity).CurrentValues.SetValues(item);
}
Otherwise, check the AddOrUpdate implementation for ideas.
Hope this help!