NHibernate Guid generator if new

I would like NHibernate to create tooltips for entities only if they are not manually installed by the user or application. Basically, when saving objects with a new Guid () (all zeros), NHibernate should generate one. When saving an object with a non-zero pointer, it should use this instead.

Am I the only option to write my own generator?

to edit . I know what is "assigned." I should have indicated that I knew about this. Since he does not do what I want to do this, this is not the option I am looking for. Writing your own generator is an option that works, but I would like something else. I suspect there is nothing else.

+6
source share
2 answers

The problem is that NH needs to know if the object is new or if it already exists. This is usually done by setting the identifier.

If you wrote your own generator, it does not solve the problem, because it is called only if the object is new.

  • You can use the assigned generator.
  • You can use the version column to indicate whether the object is new. I have not tried this, but it should work. The absence of any signs for NH, if the facility is new, causes some problems. Believe me.
  • You can also have an integer as a primary key, and a GUID as an ordinary unique field.

I would generate id in class constructor

 class Entity { Guid id; Entity(Guid id = Guid.Empty) { if (id == Guid.Empty) this.id = Guid.NewGuid(); else this.id = id; } } 
+2
source

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 that your question is a completely different option instead of deploying your own generator - is to use

 <generator class="assigned" /> 

However, you cannot use SaveOrUpdate() . Instead, you must explicitly tell NHibernate if the object should be saved or updated by calling Save () or Update () ISession. Also, you always need to manually specify the GUID for all your new objects. Its an option.

+1
source

Source: https://habr.com/ru/post/910372/


All Articles