Josh Anderson
Josh Anderson

Reputation: 6005

Fluent NHibernate - Mapping many-to-many relationship for related entities of the same type

I'm trying to figure out how to structure my entity mappings to achieve the following:

public class Document
{
    public virtual string Name { get; set; }
    // Other properties
    public IList<Document> RelatedDocuments { get; set; }
}

I'd like to have a relationship table that has ID pairs of the related Documents.

Right now I'm addressing this problem with the solution described in this SO question: Fluent Nhibernate mapping related items (crazy coincidence that the OP's name is the same as mine).

I'd rather have a single list of related items and not have to have one for RelatedTo and one for RelatedFrom. Is that possible?


To clarify, the problem I'm looking to solve is that if I relate Document A to Document B, I need Document A's RelatedDocuments list to have Document B in it, and Document B's RelatedDocuments list to have Document A in it, without having to create two relationships.

Upvotes: 0

Views: 481

Answers (1)

eulerfx
eulerfx

Reputation: 37749

Try something like this:

class Document
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<Document> Related { get; set; }

    public void RelateTo(Document other) 
    {
      this.Related.Add(other);
      other.Related.Add(this);
    }
}

class DocumentMap : FluentNHibernate.Mapping.ClassMap<Document>
{
    public DocumentMap()
    {
        Table("Documents");
        Id(x => x.Id);
        Map(x => x.Name);
        HasManyToMany(x => x.Related)
            .Table("DocumentRelations")
            .ParentKeyColumn("DocumentId")
            .ChildKeyColumn("RelatedDocumentId");
    }
}

The DocumentRelations table is the association table which specifies that RelatedDocumentId is related to DocumentId. The tables would look like:

create table Documents
(
  Id int identity primary key clustered,
  Name varchar(100)
)

create table DocumentRelations
(
 DocumentId int,
 RelatedDocumentId int,
 primary key clustered (DocumentId,RelatedDocumentId)
)

You should consider whether you need to have any data associated with the relationship itself. In that case, the related collection would be a collection of RelatedDocument instances which would have the related document as a property and the mapping would be HasMany.

Upvotes: 1

Related Questions