Hey all,
I am working with a legacy database that uses composite keys. And I am trying to use NHibernate to insert a new record into the database. NHibernate specifies that I have to create the Id manually, but when I try to insert with this id I get the message:
System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'tablename' when IDENTITY_INSERT is set to OFF.
I cannot touch any of the db settings as they are administered by head office in USA.
I found that I can do a db insert via:
insert into tablename (tablename_country_id, /*extra fields here*/) values (16, /*extra values here*/)
and the tablename_id
column is automatically incremented.
Is it possible to write some sort of a handler that allows me to create an ID
object with the CountryId
set and have it auto-increment the Id
property.
Cheers.
Example Code:
Table Definition:
CREATE TABLE [dbo].[tablename](
[tablename_country_id] [int] NOT NULL,
[tablename_id] [int] IDENTITY(1,1) NOT NULL,
-- more fields here
CONSTRAINT [pk_tablename] PRIMARY KEY
(
[tablename_country_id] ASC,
[tablename_id] ASC
)
)
Class Files:
public class ModelObject
{
public ID { get; set; }
// more properties here
}
public class ID : INHibernateProxy
{
public int Id { get; set; }
public int CountryId { get; set; }
public ILazyInitializer HibernateLazyInitializer { get { throw new ApplicationException(); } }
}
Mapping File:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model" assembly="API">
<class name="ModelObject" table="dbname.dbo.tablename" lazy="false">
<composite-id name="Id" class="ID">
<key-property name="Id" column="tablename_id" type="int" />
<key-property name="CountryId" column="tablename_country_id" type="int" />
</composite-id>
<!-- more properties here -->
</class>
</hibernate-mapping>