Click here to Skip to main content
15,881,089 members
Please Sign up or sign in to vote.
3.11/5 (2 votes)
Hi
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
Posted
Comments
GuyThiebaut 4-Jan-14 14:12pm    
I had a look on google and this may help:
http://stackoverflow.com/questions/19532982/how-to-omit-column-in-insert-query-of-hibernate-when-i-have-bean-class-of-many-f
richiej 5-Jan-14 7:57am    
Found the answer:

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

Very happy now !!! :-)
Maciej Los 5-Jan-14 13:20pm    
Please, post it as an answer to remove this question from unanswered list.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900