2016-07-08 34 views
0

我想知道是否有可能使許多表相關。實體框架一對零與不同的表

這是我現在(工作一到零或一關係之間ReportReportHeader):我要添加表命名StyleReport也給

public class Report 
{ 
    public int Id {get; set;} 
    public ReportHeader ReportHeader {get; set;} 

    [ForeignKey("ReportHeader")] 
    public int ReportHeaderId {get; set;} 
} 

public class ReportHeader 
{ 
    [Key, ForeignKey("Report")] 
    public int Id {get; set;} 

    public Report Report {get; set;} 
} 

此時表ReportHeader。因此,關係是這樣的:

Report 
|--ReportHeader 
| |-- Style 
| 
|-- Style 

之後的類應該是這樣的:

public class Report 
{ 
    public int Id {get; set;} 

    public ReportHeader ReportHeader {get; set;} 
    public Style Style {get; set;} 

    [ForeignKey("ReportHeader")] 
    public int ReportHeaderId {get; set;} 

    [ForeignKey("Style")] 
    public int StyleId {get; set;} 
} 

public class ReportHeader 
{ 
    [Key, ForeignKey("Report")] 
    public int Id {get; set;} 

    [ForeignKey("Style")] 
    public int StyleId {get; set;} 

    public Report Report {get; set;} 
    public Style Style {get; set;} 
} 

這是這麼多的樂趣......直到它想想Style類。在這一點上,我不知道如何設計它。這甚至有可能使這個班級與不同的表格有兩種關係嗎?

public class Style 
{ 
    // ??? 
    //[Key, ForeignKey("Report"), ForeignKey("ReportHeader")] 
    public int Id {get; set;} 

    public ReportHeader ReportHeader {get; set;} 
    public Report Report {get; set;} 
} 
+0

什麼是報表樣式之間所需的關係ReportHeader風格? –

+0

那麼,你的'Style'需要有兩個(可選的)FK關係 - 一個到'Report',另一個到'ReportHeader'。因此,爲這兩個參考添加兩個FK列和相應的兩個導航屬性。 –

+0

@Slava Utesinov投訴風格1:1,ReportHeader風格1:0..1 –

回答

0

在這種情況下,你應該到面具你想要的關係:一到一個多到一:

public BaseClass 
{ 
    //indeed, collection always will have zero or one items 
    public virtual ICollection<Style> styles {get; set;} 

    [NotMapped] 
    public Style style { 
     get { return styles.FirstOrDefault(); } 
     set { styles.Add(value); }; 
    } 
} 

public class Report : BaseClass 
{ 
    //other stuff... 
} 

public class ReportHeader : BaseClass 
{ 
    //other stuff... 
} 

public class Style 
{ 
    public int Id {get; set;} 

    public virtual Report report {get; set;} 
    [Index(IsUnique = true)]//to ensure that relation is exactly one-to-one 
    public int? reportId {get; set;} 

    public virtual ReportHeader reportHeader {get; set;} 
    [Index(IsUnique = true)]//to ensure that relation is exactly one-to-one 
    public int? reportHeaderId {get; set;} 
}