简体   繁体   中英

How to map identifying relationship in Entity Framework 5 code first child entity with multiple mutually exclusive parent entities

I'm using Entity Framework 5 Code First and I have the following model:

class Document
{
    public int Id {get;set;}
    public String Name {get;set;}

    public IList<Page> Pages {get;set;}
}

class DocumentTemplate
{
    public int Id {get;set;}
    public String Description {get;set;}
    public String Name {get;set;}

    public IList<Page> Pages {get;set;}
}

class Page
{
    public int Id {get;set;}
    public string Text {get;set;}
}

I know how to map an identifying relationship where the child entity has 1 parent. But I would like to map the Page entity so that it has an identifying relationship for each parent.

Also, the parent relationships are mutually exclusive. A particular page will either belong to a DocumentTemplate or a Document, not both.

Is such a mapping possible in Entity Framework 5?

I do not want to make separate entities for a Page, because they will essentially be the same, except for the parent relationship.

TIA.

I don't think you can have multiple parents, But I would consider the following option:
(Any document belong to some-template, only templates can have pages)

class Document
{
    public int Id {get;set;}
    public String Name {get;set;}
    public DocumentTemplate DocumentTemplate{get;set;}
}

class DocumentTemplate
{
    public int Id {get;set;}
    public String Description {get;set;}
    public String Name {get;set;}

    public IList<Page> Pages {get;set;}
}

class Page
{
    public int Id {get;set;}
    public string Text {get;set;}
}

this would work for you:

class Page
{
    public int Id {get;set;}
    public string Text {get;set;}

    public int? DocumentId { get; set; } // non-mandatory relationship to Document
    public int? DocumentTemplateId { get; set; } // non-mandatory relationship to DocumentTemplate

    // ... navigation properties
}

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