NHibernate中的多对多映射

NHibernate中的多对多映射

本文介绍了NHibernate中的多对多映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找使用NHibernate建立多对多关系的方法.我不确定如何在XML文件中映射它们.我还没有创建这些类,但是它们将只是基本的POCO.

I'm looking to create a many to many relationship using NHibernate. I'm not sure how to map these in the XML files. I have not created the classes yet, but they will just be basic POCOs.

人员
personId
名称

Person
personId
name

能力
CompetencyId
标题

Competency
competencyId
title

Person_x_Competency
personId
胜任力

Person_x_Competency
personId
competencyId

从本质上来说,我会在每个POCO中为另一个类创建一个列表吗?然后以某种方式使用NHibernate配置文件映射这些文件?

Would I essentially create a List in each POCO for the other class? Then map those somehow using the NHibernate configuration files?

推荐答案

您可以将多对多关系放在一个或两个类之间.这取决于您的域模型.如果将其映射到两个对象,则其中之一是相反的.

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; }
}

映射:

<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.

这篇关于NHibernate中的多对多映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 04:44