简体   繁体   中英

NHibernate Mapping By Code Many-to-One with an Intermediate Table

Here is the scenario. I have two classes, say Husband and Wife :D And the relation between these two classes are defined through a third intermediate table named People.

classes:

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

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

Tables:

Husband :: Table
  HusbandId : int

Wife :: Table
  WifeId : int

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

In the People table, RelationType = 1 indicates a marriage relation between a man and a woman where ManId == HusbandId and WomanId == WifeId.

Note that it is guaranteed that there is only one Wife for each Husband in People table. Also it is needless to say that I cannot modify the tables. It is legacy database.

Mapping:

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

Now the question is how I can have a many-to-one mapping from Husband to Wife using the intermediate table People?

So far I found an ungly-hacky solution which works but it is just 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);
       });
  }
}

The problem I am facing is that I cannot find any other way to push relationType = 1 to the generated sql. Does anyone knows how to get this done?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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