简体   繁体   English

NHibernate中的多对多映射

[英]many-to-many mapping in NHibernate

I'm looking to create a many to many relationship using NHibernate. 我希望使用NHibernate创建多对多的关系。 I'm not sure how to map these in the XML files. 我不确定如何在XML文件中映射这些。 I have not created the classes yet, but they will just be basic POCOs. 我还没有创建类,但它们只是基本的POCO。

Tables

Person
personId PERSONID
name 名称

Competency 能力
competencyId competencyId
title 标题

Person_x_Competency Person_x_Competency
personId PERSONID
competencyId competencyId

Would I essentially create a List in each POCO for the other class? 我是否会在每个POCO中为另一个类创建一个List? Then map those somehow using the NHibernate configuration files? 然后使用NHibernate配置文件以某种方式映射它们?

You can put the many-to-many relation to either class, or even to both. 您可以将多对多关系放在任一类中,甚至两者之间。 This is up to your domain model. 这取决于您的域模型。 If you map it to both, one of them is inverse. 如果将它映射到两者,则其中一个是反向的。

class Person
{
  // id ...
  IList<Competency> Competencies { get; private set; }

  // you domain model is responsible to manage bidirectional dependencies.
  // of course this is not a complete implementation
  public void AddCompetency(Competency competency)
  {
    Competencies.Add(competency);
    competency.AddPerson(this);
  }
}

class Competency
{
  // id ...
  IList<Person> Persons { get; private set; }
}

Mapping: 制图:

<class name="Person">
  <id ....>
  <bag name="Competencies" table="Person_x_Competency">
    <key column="personId"/>
    <many-to-many class="Competency" column="competencyId"/>
  </bag>
</class>

<class name="Competency">
  <id ....>
  <bag name="Persons" table="Person_x_Competency" inverse="true">
    <key column="competencyId"/>
    <many-to-many class="Person" column="personId"/>
  </bag>
</class>

Only make it bidirectional if you really need it. 如果你真的需要它,只能使它双向。

By the way: it is much better to write the classes first and create the database design afterwards. 顺便说一下:首先编写类并在之后创建数据库设计要好得多。 The database can be exported from the mapping files. 可以从映射文件导出数据库。 This is very useful. 这非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM