I'd like NHibernate to generate guids for entities only if they are not set manually by the user or application. Basically, when saving objects with new Guid() (all zeros), NHibernate should generate one. When saving an object that has a non-zero Guid, it should use that instead.
Is my only option to write my own generator?
edit Folks, I'm aware of 'assigned'. I should have specified I was aware of it. Since it doesn't do what I want it to do, it's not the option I'm looking for. Writing my own generator is an option that works, but I'd like something else. I'm suspecting there is nothing else.
The problem here is that NH needs to know if the object is new or if it already exists. It does this usually by setting the ID.
If you wrote your own generator, it doesn't solve the problem, because it is only called if the object is new.
assigned
generator. I whould generate the id in the class' constructor
class Entity
{
Guid id;
Entity(Guid id = Guid.Empty)
{
if (id == Guid.Empty) this.id = Guid.NewGuid();
else this.id = id;
}
}
Have you tried setting the unsaved-value
attribute?
<id name="Id" column="Id" type="Guid" unsaved-value="00000000-0000-0000-0000-000000000000">
<generator class="guid.comb" />
</id>
edit now I understand your question fully another option instead of rolling out your own generator is to use
<generator class="assigned" />
However you cannot use SaveOrUpdate()
. Instead you have to explicitly specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession. Also you will always need to set the GUID manually on all your NEW entities. Its an option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With