简体   繁体   中英

Mapping junction table to self

I'm struggling with mappings that uses a junction table that references the same table. The idea is to be able to track all links between the pages.

Junction table:

CREATE TABLE WikiPageLinks (
    Page int NOT NULL, 
    LinkedPage int NOT NULL
)

Main table:

CREATE TABLE WikiPages (
    Id int NOT NULL IDENTITY, 
    PageName nvarchar(50) NOT NULL, 
    Title nvarchar(50) NOT NULL, 
CONSTRAINT PK_WikiPages PRIMARY KEY (Id)
)

And class:

public class WikiPage
{
    public virtual int Id { get; protected set; }
    public virtual IEnumerable<WikiPageLink> BackReferences {get;}
    public virtual IEnumerable<WikiPageLink> References {get; }
}
  • BackReferences = Current page is WikiPageLinks .LinkedPage
  • References = Current page is WikiPageLinks.Page

How should the mapping look like?

if there are no additional columns in the link then i would cut it out

public class WikiPage
{
    public virtual int Id { get; protected set; }
    public virtual IEnumerable<WikiPage> BackReferences { get; }
    public virtual IEnumerable<WikiPage> References { get; }
}

// WikiPageMap : ClassMap<WikiPage>
public WikiPageMap()
{
    ...
    HasManyToMany(wp => wp.References)
        .Table("WikiPageLinks")
        .ParentKeyColumn("parent_page_id")
        .ChildKeyColumn("referenced_page_id");

    HasManyToMany(wp => wp.BackReferences)
        .Table("WikiPageLinks")
        .ParentKeyColumn("referenced_page_id")
        .ChildKeyColumn("parent_page_id")
        .Inverse();

    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM