Saturday, May 22, 2010

Updating a detached entity with EF4

With the introduction of EF4 we now have the ability to update entities without having to query the database first. This was always a performance hit with EF1, but a necessary hit. I’m not going to get into that, lets see the code.


void UpdateBook(Book book) {
using(var ctx = new BookEntities()){
ctx.Books.Attach(book);
ctx.ObjectStateManager.ChangeObjectState(
book,
EntityState.Modified);
ctx.SaveChanges();
}
}

Pretty easy. The drawback is that the ChangeObjectState method marks every property of the book object as being Modified. So when EF generates the SQL Update statement, every column in the database for this book record will be updated. This really isn’t an issue if you’ve set all the properties on the book entity. Where it becomes an issue is if you are trying to update only one property. For instance you just want to update book.Title, well if the Title property is the only property you set, then Author, Copyright, NumberOfPages, etc. will all get overwritten with null in the database.

No comments: