Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate Guid generator if new

Tags:

nhibernate

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.

like image 206
Jerome Haltom Avatar asked Mar 09 '12 20:03

Jerome Haltom


2 Answers

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.

  • You could use the assigned generator.
  • You could use a version column to indicate if the object is new. I never tried it this way, but it should work. NOT having any indication for NH if the object is new causes quite some troubles. Believe me.
  • You could also have a integer as primary key and the GUID as regular unique field.

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;
  }
}
like image 89
Stefan Steinegger Avatar answered Nov 09 '22 16:11

Stefan Steinegger


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.

like image 41
Rippo Avatar answered Nov 09 '22 17:11

Rippo