开发者

What is best way to use NHibernate to map a constrained many-to-many relationship?

开发者 https://www.devze.com 2023-03-23 21:31 出处:网络
I have two entities represented by two tables in the database, joined by a linking table with a unique constraint on each of the two foreign keys. (See this question for details). The linking table al

I have two entities represented by two tables in the database, joined by a linking table with a unique constraint on each of the two foreign keys. (See this question for details). The linking table allows for a many-to-many relationship, but the unique constraint ensures that ther开发者_如何学Pythone is only a one-to-one relationship in practice.

A good analogy to the problem is cars and parking garage spaces. There are many cars and many spaces. A space can contain one car or be empty; a car can only be in one space at a time, or no space (not parked).

We have a Cars table and a Spaces table and the linking table called Parking. Here is the linking table:

create table parking (
  car_id references car,
  space_id references space,
  unique car_id,
  unique space_id
);

Is there a way to map this relationship in NHibernate such that each entity holds a single property representing the related entity, rather than a collection?


it is possible like this

class Car
{
    public Space Space { get; set; }
}

public CarMap()
{
    Join("parking", join =>
    {
        join.KeyColumn("car_id");
        join.References(car => car.Space, "space_id");
    });
}

in hbm something along:

<class name="car">

  <join table="parking">
     <many-to-one name="Space" column="space_id"/>
  </join>
</class>
0

精彩评论

暂无评论...
验证码 换一张
取 消