Saturday, 1 March 2014

Nice Entity Framework trick


There is a cool trick for deleting a item from a database table using the Entity Framework.

Usually you would delete an item like this:

public bool DeleteOrder(int id)
{
 Order order = contextDb.find(id);
contextDb.Remove(order);
contextDb.SaveChanges();
}

However if you want some improvement, on performance, You could re-write the above code
like this:

public bool DeleteOrder(int id)
{
 Order orderToNuke = new Order {ID:id};
contextDb.Entry(orderToNuke).State.Deleted;
contextDb.SaveChanges();
}

Entity Framework is smart to know that that order marked with the  Stated.Deleted it needs to be removed from the database.