gpt4 book ai didi

c# - 使用 NHibernate 插入带有复合键的记录

转载 作者:太空狗 更新时间:2023-10-29 23:53:15 26 4
gpt4 key购买 nike

我正在使用使用复合键的遗留数据库。我正在尝试使用 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 列会自动递增。

是否可以编写某种处理程序,允许我使用 CountryId 集创建一个 ID 对象并让它自动递增 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>

最佳答案

我认为您可以将标识列设置为复合键中的一个键。

我知道在 fluentnhibernate 中我有一个复合键的标识列名称

关于c# - 使用 NHibernate 插入带有复合键的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/994662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com