tags:

views:

1395

answers:

3

Id columns can specify a generator. Perfect.

However, I have a situation in which I need to assign a generated value to a property column if it is null. Think something along the lines of an invoice table where there's a surrogate primary key column and an Invoice Number column.

CREATE TABLE dbo.Invoice (InvoiceId INT NOT NULL PRIMARY KEY IDENTITY(1,1), InvoiceNumber INT NOT NULL, InvoiceDate DATETIME NOT NULL, remaining columns...)

This isn't a default value. The Invoice Number might have certain rules around it's generation. I have a C# class that handles the actual generation, I just need to find a way to populate the value of the property on the Invoice class.

Ideally I'd be able to specify a generator for a property like I do for an Id in the mapping. Unfortunately, that doesn't seem possible from what I can determine. I'm hoping I'm wrong.

I have other, non-nHibernate options I could employ like using a trigger, inserting the generation into the provider. However, I'd like to keep it a configuration option rather than a coding option.

Does anyone know if a such an ability exists?

A: 

You mean you want to provide a default-value ?

I would say that this should be something that you should specify at the DB level ...

If you really want that NHibernate takes care of this, I think you should create an Interceptor that would set the value of that property when it is null at flush-time.

Or, you can specify the default value in your entity, by giving the property a default-value in the constructor.

Frederik Gheysels
Not a default value. A unique value that's generated when a new entity is saved. I'd forgotten about interceptors.
Cory
+2  A: 

NHibernate expects that you will define all these rules in your domain classes - for example, in the constructors.

Justice
A: 

Sorry for the late answer, but I recently ran into the same problem as you. I backtraced a bit in the NHibernate source and seems like I found a solution.

You can use the NHibernate.Id namespace for Guid generation. There's 2 viable options - letting your client generate the Guid or letting the native DB do it.

These are the classes you need:

  • NHibernate.Id.NativeGuidGenerator //DB generation
  • NHibernate.Id.GuidGenerator //Client generation

Using the NHibernate.Id.NativeGuidGenerator-class can be accomplished by something like this:

public Guid GetNewSessionId()
{
    NHibernate.Id.NativeGuidGenerator guidGen = new NHibernate.Id.NativeGuidGenerator();
    return (Guid)(guidGen.Generate((NHibernate.Engine.ISessionImplementor)anOpenSession, null));
}

Good luck with it :)

cwap