Nhibernate Identity mapping when using "newsequentialid" in DB

1.1k Views Asked by At

I'm using NHibernate to map my objects to the DB. One of these object is called "Attachment". its ID is generated using the "newsequentialid" in MS SQL server 2008 (as the Default Value or Binding) to create the Guid for the id column.

Now what i want is that when a new Attachment is inserted then NHibernate will allow the SQL Server to create the Guid using the newsequentialid. Thing is that the i keep getting an exception "null identifier" when trying to save a new Attachment where the id is not set (Guid.Empty)

here is my HBM file:

<class name="DataObjects.Services.NHAttachment, DataObjects, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" mutable="false" table="Attachments">
    <id name="Id" column="Guid" type="Guid" >
      <generator class="native"  />
    </id>.....

As you can see the ID is set with a generator class as native.

Thanks for all the help in advance!! :)

2

There are 2 best solutions below

1
On

As of 2013-06-12, NHibernate 3.3 seems to not support NEWSEQUENTIALID correctly because I tried it and it fails.

For example having

   sec_UserRole
   (UserRoleId UNIQUEIDENTIFIER DEFAULT NewSequentialId(), 
    UserId, 
    RoleId, 
    CreationDate, 
    CreatedBy)

With mapping

    public SecUserRoleMapping()
    {
        Table("sec_UserRole");
        Id(x => x.UserRoleId, m => m.Generator(Generators.Native);

I get the following SQL:

declare @p0 uniqueidentifier
declare @p1 uniqueidentifier
declare @p2 datetime2
declare @p3 uniqueidentifier
    set @p0 = '00000000-0000-0000-0000-000000000001'
    set @p1 = '383b75fd-6829-41b5-b8a6-63f1dc1acef0'
    set @p2 = '12/6/2013 5:09:56 AM'
    set @p3 = '00000000-0000-0000-0000-000000000001'

INSERT 
    INTO
        sec_UserRole
        (UserId, RoleId, CreationDate, CreatedBy) 
    VALUES
        (@p0, @p1, @p2, @p3);
    **select
        SCOPE_IDENTITY();**

Note the ** highlighted part. It's trying to get the last IDENTITY! when it should use the OUTPUT clause and get it with an output parameter. http://jwwishart.wordpress.com/2009/08/05/returning-the-newsequentialid-after-insert-using-the-output-clause/

So my next move is to try to create a new custom generator. http://nhibernate.info/doc/howto/various/creating-a-custom-id-generator-for-nhibernate.html

0
On

If you want to tell NHibernate to create a GUID in the database schema, then I think the following should work:

<id name="Id" column="Guid" type="Guid">
  <generator class="guid" />
</id>