NHibernate映射通过代码多对一与中间表

时间:2014-04-10 23:08:03

标签: c# nhibernate-mapping many-to-one mapping-by-code

以下是该方案。我有两个班,比如丈夫和妻子:D这两个班级之间的关系是通过名为People的第三个中间表来定义的。

类:

class Husband
{
  public virtual int HusbandId { get; set; }
  public virtual Wife Wife { get; set; }
}

class Wife
{
  public virtual int WifeId { get; set; }
  ...
}

表:

Husband :: Table
  HusbandId : int

Wife :: Table
  WifeId : int

People :: Table
  PeopleId : int
  ManId : int
  WomanId : int
  RelationType : int

在People表中,RelationType = 1表示男人和女人之间的婚姻关系,其中ManId == HusbandId和WomanId == WifeId。

请注意,保证每个Husband in People表中只有一个妻子。不用说,我不能修改表格。它是遗留数据库。

映射:

class HusbandMap : ClassMapping<Husband>
{
  public HusbandMap()
  { 
    Id(x => x.HusbandId);
    ManyToOne(x => x.Wife); // <-- How to make this mapping work ?
  }
}

class WifeMap : ClassMapping<Wife>
{
  public WifeMap()
  {
    Id(x => x.WifeId);
  }
}

现在的问题是我如何使用中间表人物从丈夫到妻子的多对一映射?

1 个答案:

答案 0 :(得分:0)

到目前为止,我发现了一个 ungly-hacky 解决方案,但它只是BAD:D

class HusbandMap : ClassMapping<Husband>
{
  public HusbandMap()
  { 
    Id(x => x.HusbandId);
    Join("People", j =>
       {
          j.Key(x => x.Column("manId and relationType = 1"); //here is the sql injection hack :D
          j.ManyToOne(x => x.Wife);
       });
  }
}

我遇到的问题是我找不到任何其他方法将relationType = 1推送到生成的sql。有谁知道怎么做到这一点?