2012-08-28 44 views
0

我试图找出如何构建我的实体映射实现如下:功能NHibernate - 映射许多一对多的关系为同一类型的相关实体

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

我想有一个关系表,它具有相关Document的ID对。

现在我正在用这个SO问题中描述的解决方案解决这个问题:Fluent Nhibernate mapping related items(疯狂的巧合,OP的名字和我一样)。

我宁愿有一个相关项目的单一列表,不必有一个为RelatedTo和一个为RelatedFrom。那可能吗?


为了澄清,我要解决的问题是,如果我将文档A关联到文档B,我需要文档A的 RelatedDocuments列表中包含文档B,文档B的 RelatedDocuments列表中包含文档A, 而不必创建两个关系

回答

1

尝试这样:

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"); 
    } 
} 

DocumentRelations表是关联表指定RelatedDocumentId有关DocumentId。该表将如下所示:

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

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

你应该考虑是否需要与关系本身相关的任何数据。在这种情况下,相关集合将是一个RelatedDocument实例的集合,它将相关文档作为一个属性,映射将为HasMany。

+0

我还没有尝试过这一点,但似乎只有我手动重复所有相关实体之间的关系时,建议才会起作用。为了澄清我期待的结果,如果我在DocA中添加与DocB和DocC的关系,我希望在DocB的相关列表中看到DocA和DocC,在DocC的列表中看到DocA和DocB等。 –

+0

因此, (http://en.wikipedia.org/wiki/Transitive_relation)和[symmetric](http://en.wikipedia.org/wiki/Symmetric_relation)?意思是,如果A与B和C有关,那么B和C都与A和彼此有关? – eulerfx

+0

不可传递,只是对称的。因此,如果A与B相关且C与A相关,则与A相关的项目列表将是B,C。 –

相关问题