NHibernate:插入在不同列上设置标识值的实体

发布于 2024-10-26 06:33:49 字数 630 浏览 6 评论 0原文

NHibernate 和 Sql Server 是否可以插入一个实体并将其中一个列值设置为新生成的标识?

在纯sql中,我可以通过添加默认值来做到这

一点创建表:

create table Test
   id int identity,
   name varchar(12),
   parentId int NOT NULL

添加约束:

alter table Test constraint ... default ident_current('Test') for parentId

然后跳过parentId或使用DEFAULT关键字:

insert into Test values('TEST')
insert into Test values('TEST', DEFAULT)

如果我错了,请纠正我,但我认为上述语句永远不会是由 NHibernate 生成?

现在,我首先保存我的实体,然后使用新创建的身份更新它。这种情况会破坏数据库结构,因为我必须使该特定列接受 NULL。

起初我认为这很容易,但现在,几个小时后我仍然找不到答案:/

提前致谢

Is it possible with NHibernate and Sql Server to insert an entity and set one of the column values to the newly generated identity?

In pure sql I can do it by adding the default value

Create the table:

create table Test
   id int identity,
   name varchar(12),
   parentId int NOT NULL

Add a constraint:

alter table Test constraint ... default ident_current('Test') for parentId

And afterwards skip the parentId or use the DEFAULT keyword:

insert into Test values('TEST')
insert into Test values('TEST', DEFAULT)

Correct me if I'm wrong but I think that the above statements are never going to be generated by NHibernate?

For now I'm first saving my entity and then updating it with the newly created identity. This case brakes the db structure as I had to make that particular column accept NULLs.

At first I though this is going to be easy, but now, after several hours I still can't find the answer :/

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

洛阳烟雨空心柳 2024-11-02 06:33:49

您可以使用属性映射。对于数据库设置的默认值,请使用generated="insert"。对于 Fluent NHibernate 映射,请使用 .Generated().Insert()

编辑:

public class Test
{
    private Test _parent;

    public Test()
    {
        _parent = this;
    }

    public Test Parent
    {
        get { return _parent == this ? null : _parent; }
        set { _parent = value ?? this; }
    }
}

You can accomplish this using the generated attribute in property mapping. For defaults set by the database, use generated="insert". For Fluent NHibernate mapping use .Generated().Insert().

EDIT:

public class Test
{
    private Test _parent;

    public Test()
    {
        _parent = this;
    }

    public Test Parent
    {
        get { return _parent == this ? null : _parent; }
        set { _parent = value ?? this; }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文