Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reliably determine that an entity is transient?

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?

like image 494
Ilian Avatar asked Nov 22 '25 14:11

Ilian


1 Answers

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.

like image 122
Thilak Nathen Avatar answered Nov 25 '25 03:11

Thilak Nathen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!