如何创建 NHibernate HasManyToMany 关系 [英] How to create NHibernate HasManyToMany relation
问题描述
我知道有关于 HasManyToMany 的问题,但这次我想将几个字段放入中间表中,例如描述、创建日期".
I know there are questions about HasManyToMany but this time I want to put couple fields into middle table like 'Description, CreationDate'.
对于我的情况,我不想以两种方式绑定.我有公司、个人和地址表.每个公司或个人可能有 1 个以上的地址.在这种情况下我该怎么办?类和映射的代码应该怎么写?
For my situation I don't want to bind two way. I have company, person and address tables. And every company or person may have more than 1 address. In this situation what should I do? How should I write the code of classes and mappings?
您可以在下面看到表格:
Below you can see the tables:
推荐答案
在这种情况下,答案很简单.不要使用多对多.使用配对对象.正是出于您提到的原因:使用更多属性扩展配对对象:
In this case the answer is pretty simple. Do not use many-to-many. Use pairing object. Exactly for the reasons you've mentioned: Extend the pairing object with more properties:
在此处查看 24.最佳做法,引用:
真正多对多关联的良好用例很少见.大多数情况下,您需要存储在链接表"中的附加信息.在这种情况下,最好使用两个一对多关联到一个中间链接类.事实上,我们认为大多数关联都是一对多和多对一的,在使用任何其他关联方式时你应该小心,问问自己是否真的有必要.
Don't use exotic association mappings.
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.
换句话说,创建从 boht 端引用配对对象的 one-to-many
关系,以及从配对对象引用的 many-to-one
关系.
Other words, create the one-to-many
relations refering the pairing objects from boht ends, and many-to-one
from the pairing object.
还要检查这些:
地址和公司的示例.第一个配对对象
An example of the Address and Company. First Pairing object
public class AddressCompany
{
// the relation to both sides
public virtual Address Address { get; set; }
public virtual Company Company { get; set; }
// many other settings we need
public virtual string Description { get; set; }
public virtual DateTime CreationDate { get; set; }
...
}
地址和公司简介:
public class Address
{
public virtual IList<AddressCompany> Companies { get; set; }
...
}
public class Company
{
public virtual IList<AddressCompany> Addresses { get; set; }
...
}
映射符合预期:
public AddressMap()
{
HasMany(x => x.Companies)
...
}
public CompanyMap()
{
HasMany(x => x.Addresses)
...
}
public AddressCompanyMap()
{
References(x => x.Address)..
References(x => x.Company)..
...
}
所以,这代表了 Pairing 对象
So, this is representing the Pairing object
好吧,但现在我们可以找到一些在某个日期之后创建的公司:
Well, but now we can find some Companies Created after a date:
var subquery = QueryOver.Of<AddressCompany>()
.Where(c => c.CreationDate > new DateTime(2000, 1, 1))
.Select(c => c.Company.ID);
var query = session.QueryOver<Company>()
.WithSubquery
.WhereProperty(c => c.ID)
.In(subquery)
...;
这样我们也可以通过地址过滤公司...
This way we can also filter Company over the Address...
这篇关于如何创建 NHibernate HasManyToMany 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!