Reputation: 6005
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 Document
s.
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?
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
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