Tamas Ionut
Tamas Ionut

Reputation: 4410

Nhibernate mapping between tables that have a intermediate table in between

I have the following code:

public class Hotel
{
  public int ID
  {  
    get;set
  } 

  public IList<Photo> Photos
  {
    get;set;
  }
  //...other code
}

public class Photo
{
  public int ID
  {
     get;set;
  }
  //...other fields
}

In the database, I have the following tables:

Photo: ID, Url, //.. other fields
HotelPhoto:ID, PhotoID, HotelID
Hotel:ID, Location, //..other fields

with relationships between Hotel <--> HotelPhoto and HotelPhoto <--> Photo.

My question is: Can I configure somehow a mapping between Hotel class and Hotel table to get a list of Photo without creating a new class HotelPhoto? ( I want a list of photos, not a list of HotelPhoto from which to get my photos).

Somehow I want to access the Photo table from the Hotel class without any class HotelPhoto, knowing that the table HotelPhoto contains only the IDs of Hotel and Photo table.

Thanks in advance, Tamash

Upvotes: 1

Views: 759

Answers (1)

Andreas
Andreas

Reputation: 5309

You can use a many-to-many-mapping e.g.:

The hotel mapping file, should contain sth. like this:

<set name="Photos" table="HotelPhoto">
  <key column="HotelId" />
  <many-to-many class="Photo" column="PhotoId"/>
</set>

For the photo mapping file you can use sth. like this:

<set name="Hotels" table="HotelPhoto">
  <key column="PhotoId" />
  <many-to-many class="Hotel" column="HotelId"/>
</set>

Note, that the mapping is not tested and assumes that a Photo has a list of hotels (otherwise your db-schema does not make sense for me).

You can find the documentation here. http://nhibernate.info/doc/nh/en/index.html#collections-ofvalues

Upvotes: 3

Related Questions