using nHibernate to insert a new object to SQL Server gives error about identity insert not being turned off

326 views
Skip to first unread message

Richard Jacobs

unread,
Jan 4, 2014, 2:54:29 PM1/4/14
to nhibernate-...@googlegroups.com

I have been pulling my hair out on this for a couple of hours at least now.

So I am using nhibernate to map my db to my code. In the DB I have table called "Product" which has a column called "ProductId" which is the primary key and also marked as an identity column in sql server 2012.

My class' mapping with the Id columned defined as:

Id(x => x.ProductId, mapper => mapper.UnsavedValue(0));

However after creating a new Product object and trying to save it I get the following error and inner exception:

{"could not execute batch command.[SQL: SQL not available]"}

Cannot insert explicit value for identity column in table 'Products' when IDENTITY_INSERT is set to OFF.

The exception is pretty clear and the product Id is set to 0. How do I tell nHibernate to not supply the Id column when creating a new object in the database?

Any help greatly appreciated

thanks

Darren Kopp

unread,
Jan 4, 2014, 5:09:13 PM1/4/14
to nhibernate-...@googlegroups.com
you need to call mapper.Generator(Generators.Identity) or something like that.

Richard Jacobs

unread,
Jan 5, 2014, 7:56:33 AM1/5/14
to nhibernate-...@googlegroups.com
I found the answer:

Id(x => x.ProductId
  , mapper =>
  {
    mapper.UnsavedValue(0)
    mapper.Generator(Generators.Native)
    ..
  });

So very happy now ! :-)

Oskar Berggren

unread,
Jan 8, 2014, 12:53:41 PM1/8/14
to nhibernate-...@googlegroups.com
In the future, please direct questions about using NHibernate to the nhuser mailing list.

/Oskar



2014/1/5 Richard Jacobs <rich.s...@googlemail.com>

--
 
---
You received this message because you are subscribed to the Google Groups "nhibernate-development" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nhibernate-develo...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages