Reputation: 5355
With NHibernate, how does one reliably check that a given entity is transient (i.e. hasn't been persisted yet)? The resources I have seen recommend something similar to this:
public bool IsTransient()
{
return this.Id == default(Guid);
}
Assuming my already persisted entity has an integer ID and it is somehow equal to 0, wouldn't this method fail?
Upvotes: 3
Views: 6232
Reputation: 1333
If 0 is a valid primary key in your context, then yes, that would be unreliable.
Basically, the "unsaved-value" on the id of the object determines if it's transient or persistent. By default, it's set to null or default() for the type. You can choose to set this manually when you do your mapping.
As long as your logic in the code above conforms to what Nhibernate believes is a transient object, you're good. And Nhibernate will take any object whose Id property equals that of "unsaved-value" to be transient.
Upvotes: 4