多对多与额外的列 nhibernate [英] many-to-many with extra columns nhibernate

查看:27
本文介绍了多对多与额外的列 nhibernate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个表UsersGroups.这些表(在数据库中)与 UGlink 链接表一起使用.现在除了主外键,链接表还有一个额外的列:Date.

So I have two tables Users and Groups. These tables are (in the database) liked with a UGlink link table. Now except for the primary-foreign keys the link table have an extra column: Date.

据我所知,这意味着我必须有两个多对一,链接在中间".

From what I understand this means that I have to have two Many-to-One, with the link "in the middle".

但是,由于我几乎从不对额外的列值感兴趣,是否有办法避免链接?那就是我希望能够写:

However since I'm almost never is interested of the extra column value, is there anyway to avoid the link? That is I want to be able to write:

thisUser.Groups

获取组,而不是:

thisUser.UGlinks.Group

推荐答案

many-to-many,没有作为实体的配对表的显式映射 - 在 NHibernate 中当然支持.因此,如果 Date 列是自动生成的,或者可以为空 (不必由 app/NHiberante 插入),我们可以这样做:6.8.双向关联

The many-to-many, without the explicit mapping of the pairing table as an entity - is in NHibernate of course suported. So, in case, that the Date column is autogenerated, or nullable (does not have to be inserted by app/NHiberante), we can do it like here: 6.8. Bidirectional Associations

<class name="User">
    <id name="Id" column="Uid"/>
    ...
    <bag name="Groups" table="UGlink" lazy="true">
        <key column="Uid"/>
        <many-to-many class="Group" column="Gid"/>
    </bag>
</class>

<class name="Group">
    <id name="id" column="Gid"/>
    ...

    <!-- inverse end -->
    <bag name="Users" table="UGlink" inverse="true" lazy="true">
        <key column="Gid"/>
        <many-to-many class="User" column="Uid"/>
    </bag>
</class>

所以,我们拥有的是一个映射,其中 NHiberante 确实关心配对表,我们可以这样做:

So, what we have is a mapping, in which NHiberante does care about the pairing table, and we can do:

thisUser.Groups

但如果我可以建议,不要使用 many-to-many.多对一与配对对象是(我会说)更好的解决方案,因为它将支持按组搜索用户,反之亦然.

But if I could suggest, do not go with many-to-many. The many-to-one with pairing object is (I'd say) better solution, because it will support searching Users by Groups and vice versa.

参见第 24 章最佳实践,引用:

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

真正多对多关联的良好用例很少见.大多数情况下,您需要存储在链接表"中的附加信息.在这种情况下,最好使用两个一对多关联到一个中间链接类.事实上,我们认为大多数关联都是一对多和多对一的,在使用任何其他关联方式时你应该小心,问问自己是否真的有必要.

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.

这里有一些更详细的解释如何在没有多对多的情况下做到这一点:Nhibernate:如何表示多对多关系一对多关系?

Here is some more detailed explanation how to do it without many-to-many: Nhibernate: How to represent Many-To-Many relationships with One-to-Many relationships?

这篇关于多对多与额外的列 nhibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆