tags:

views:

64

answers:

1

I find myself writing code like the following quite a lot:

if (myEntity.Id == default(Guid))
   Session.Save(myEntity);

What is the best way to check if an entity is already persistent (and therefore doesnt need to be saved)?

Am I doing something wrong writing code like this?

+3  A: 

That's what I do except I usually use an IsNew() or IsTransient() method in a base class or extension that performs this check. Then the code becomes:

public Boolean IsTransient(){
 return this.Id == default(Guid);
}

Don't forget that the Session.SaveOrUpdate(entity) method will cause an update of a persisted entity (as opposed to an insert) so you could use this method and ignore the check. I prefer to do the check though.

Michael Gattuso