我正在使用一个使用复合键的旧数据库。我正在尝试使用 NHibernate 将新记录插入数据库。NHibernate 指定我必须手动创建 ID,但是当我尝试使用此 ID 插入时,我收到以下消息:
System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'tablename' when IDENTITY_INSERT is set to OFF.
我无法触摸任何数据库设置,因为它们由美国总部管理。
我发现我可以通过以下方式进行数据库插入:
insert into tablename (tablename_country_id, /*extra fields here*/) values (16, /*extra values here*/)
并且该tablename_id
列会自动递增。
是否可以编写某种处理程序,允许我ID
使用集合创建一个对象CountryId
并让它自动增加Id
属性。
干杯。
示例代码:
表定义:
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
)
)
类文件:
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(); } }
}
映射文件:
<?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>