gpt4 book ai didi

Nhibernate:如何用一对多关系表示多对多关系?

转载 作者:行者123 更新时间:2023-12-02 14:47:55 26 4
gpt4 key购买 nike

我在网上看到一篇文章(我已经找不到那篇文章可以引用了),说多对多关系可以用一对多关系代替。有人可以举个例子吗?

最佳答案

我刚刚提出这个问题,然后意识到缺少任何答案。这是一种耻辱,虽然我经常指出这个 NHibernate 文档声明:24. Best Practices

不要使用奇异的关联映射。

Good usecases for a real many-to-many associations are rare. Most of the time you need additional information stored in the "link table". In this case, it is much better to use two one-to-many associations to an intermediate link class. In fact, we think that most associations are one-to-many and many-to-one, you should be careful when using any other association style and ask yourself if it is really neccessary.

看一下 23.2. Author/Work 下的示例。 Extract,AuthorWork 之间多对多关系的简化版本:

<class name="Work" table="works" ...>
<id name="Id" column="id" generator="native" />
...
<set name="Authors" table="author_work" lazy="true">
<key>
<column name="work_id" not-null="true"/>
</key>
<many-to-many class="Author">
<column name="author_id" not-null="true"/>
</many-to-many>
</set>
</class>

及其多对多目标作者:

<class name="Author" table="authors">
...
<set name="Works" table="author_work" inverse="true" lazy="true">
<key column="author_id"/>
<many-to-many class="Work" column="work_id"/>
</set>
</class>

所以,如果我们想在加载时订购一组作品,我们确实遇到了问题。配对表中没有列。但更重要的是,没有办法如何管理这样的专栏。

我们能做的就是引入 Pair 对象:AuthorWork 并根据需要扩展 Pair 表

public class AuthorWork
{

public virtual Author Author { get; set; }
public virtual Work Work { get; set; }
public virtual int OrderBy { get; set; }
}

作者作品的映射

<class name="AuthorWork" table="author_work">
...
<many-to-one name="Author" column="author_id" />
<many-to-one name="Workr" column="work_id" />
<property name="OrderBy" />

有了这个,我们就可以将多对多映射转换为一对多,例如作者集合:

<set name="Authors" lazy="true"
order-by="OrderBy">
<key column="work_id" not-null="true"/>
<one-to-many class="AuthorWork" />
</set>

我们可以管理实体 AuthorWork,设置 OrderBy 列,从而有效地使用配对表。

注意:必须同意文档中的建议。需求越多,我们就越高兴,因为我们确实有办法管理关系!

关于Nhibernate:如何用一对多关系表示多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15510748/

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