gpt4 book ai didi

fluent-nhibernate - HasMany 非空外键

转载 作者:行者123 更新时间:2023-12-04 07:41:44 25 4
gpt4 key购买 nike

我有两个类(例如简化):

public class Data
{
public int Id {get; set;}
public string Value { get; set; }
}
public class DataContainer
{
public int Id {get; set;}
public IList<Data> DataPoints { get; set; }
}

基本上,DataContainer 类有一组数据(和其他未显示的属性)。 Data 类不知道 DataContainer,但它不能存在于一个之外。我为此使用了 HasMany 关系。

我像这样映射 DataContainer:

Id(x => x.Id);
HasMany<Data>(x => x.DataPoints)
.Not.KeyNullable()
.Cascade.All();

为数据生成的 SQL 如下所示:

create table [Data] (
[Id] INT IDENTITY NOT NULL,
[DataContainer] INT null,
primary key ([Id])
)
alter table [Data]
add constraint FK173EC9226585807B
foreign key ([DataContainer])
references [DataContainer]

问题是我不希望[DataContainer] INT null,而是我希望它不允许空值

[DataContainer] INT not null

我以为 .Not.KeyNullable() 会这样做,但它似乎不起作用。

谢谢。

最佳答案

我有完全相同的映射和相同的结果,但查看由 Fluent 生成的 hbm.xml,它看起来像它在这里能做的。集合映射看起来像这样(注意“key”元素上的“not-null”属性):

<bag cascade="all" name="Items" mutable="true">
<key foreign-key="FK_MyEntity2_MyEntity1" not-null="true">
<column name="MyEntity1_Id" />
</key>
<one-to-many class="MyNs.MyEntity2, MyAssembly, Version=0.4.700.0, Culture=neutral, PublicKeyToken=null" />
</bag>

因此我认为这是一个 NHibernate 问题而不是一个 Fluent 问题。以下摘自最新的 NHibernate 引用(3.0.0,但我很确定 2.1.2 也是如此)的第 6.4 章

Very Important Note: If the <key> column of a association is declared NOT NULL, NHibernate may cause constraint violations when it creates or updates the association. To prevent this problem, you must use a bidirectional association with the many valued end (the set or bag) marked as inverse="true". See the discussion of bidirectional associations later in this chapter.

所以我的猜测是 NHibernate 在为此映射生成 DDL 时简单地忽略了“not-null”属性,并且解决方案是按照上面的建议使关联双向(绝对有效但可能不适合您的场景)或实时带有 NULL 列。

关于fluent-nhibernate - HasMany 非空外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4283022/

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