views:

414

answers:

1

Hi there!

Looking for an answer on how to configure NHibernate to support my scenario, an many-to-many map with an objectified relation.

I have a colection of Person:s with relations to other Person:s. Each of the relations have an attribute specifying what type of relation they have. In an RDB this is done by using a many-to-many table with the relation type specified in that table, model can then be extended by allowing more types, e.g. "close-friend" and "arch-enemy".

I would like to be able either to query a Person object to return all related Persons by type

<IList>Person myEnemies =  myPerson.getRelatedPersons(relationType.Enemy)

or

<IList>Person myFriends = myPerson.getRelatedPersons(relationType.Friend)

Another (less extensible) solution would be to statically in the class specify what other relations exist:

public class Person   
{   
  public virtual int Id { get; private set; }   
  public virtual string FirstName { get; set; }   
  public virtual string LastName { get; set; }   
  public virtual IList<Person> Friends { get; set; }   
  public virtual IList<Person> Enemies { get; set; }   
}

Right now I have to use a legacy database with a "Person" table as well as a "PersonPerson" table. The "PersonPerson" table holds the relation type as an integer.

I've trying to do this using syntax like below without success this far...

// How to specify type=1  here?
HasManyToMany(x => x.Friends).WithTableName("Person_Person"); 

// How to specify type=2  here?
HasManyToMany(x => x.Enemies).WithTableName("Person_Person");

Any tips/solution on mapping this with (fluent) NHibernate?

BR

/Jens

+1  A: 

The first example you speak of sounds like you need to investigate an inheritance mapping, but I'm not sure how that'd work with the extra table involved.

The second example you should just be able to use the Where clause.

HasManyToMany(x => x.Friends)
  .WithTableName("Person_Person")
  .Where("type = 2");
James Gregory
Great!I guess that I have to include a new class, "RelatedPerson", to support first case./J
JensJ