Reputation: 25628
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?
Upvotes: 1
Views: 1113
Reputation: 13200
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.
Upvotes: 5