Friday, December 23, 2011

.NET Entity Framework: Detect if an Entity is new

When I'm using Entity Framework (EF) I'd like to have a Save() method that I can call without having to know what the state of the object is. I don't care if the object should be inserted or updated, that's up to the Save() method to find out.

In Entity Framework you can find out the state of an object by calling context.ObjectStateManager.GetObjectStateEntry(obj). To be able to use this method, your object needs to be attached to the context. If not, it will raise an InvalidOperationException. And that will be the case if you are saving an object that was just created (and not attached yet).

So what I do is using an extension method to determine what to do in the Save() method:

public static bool IsNew(this EntityObject entity)
{
  return entity.EntityKey == null || entity.EntityKey.IsTemporary;
}

If an object isn't attached yet, its EntityKey will be null. Otherwise, if it's attached but new, its EntityKey will be indicated as temporary.

The Save() mehtod calls the IsNew() method and acts accordingly.
private void Save(Product product)
{
  if (product.IsNew())
  {
    Insert(product);
  }
  else
  {
    Update(product);
  }
}

No comments:

Post a Comment