Saturday, May 22, 2010

Deleting a detached entity with EF4

As unconventional as it may have seemed, it was the reality. With EF1 you had to first query the database to get the entity you wanted to delete. Talk about a waste of time, but the ObjectContext needs to be aware of the entity somehow. In my previous post I talked about how to update a detached entity with EF4. Now deleting a detached entity is just as easy.


void DeleteBook(Book book)
{
using(var ctx = new BookEntities())
{
ctx.Books.Attach(book);
ctx.DeleteObject(book);
ctx.SaveChanges();
}
}

Again pretty easy and should improve on performance.

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.