1

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

Xavier
  • 3,919
  • 3
  • 27
  • 55
user3161050
  • 111
  • 1
  • 14

1 Answers1

2

The generator used for the "ID" must be native (or identity), i.e. driven by DB engine. The mapping should be like this:

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

See

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335