2011-08-10 40 views
12

我們使用EF 4.1和流利API從舊數據庫獲取數據(無法修改數據庫)。我們在創建相關列不是主鍵和外鍵的兩個表之間創建關係時遇到問題。使用Entity Framework創建非主鍵字段的關聯4.1 Fluent API

通過下面的類,我們將如何配置Report和RunStat之間的一對多關係,以便Report.RunStats將返回ReportCode字段相同的所有RunStat實體。

public class Report 
{ 
    [Key] 
    public int ReportKey { get; set; } 
    public string Name { get; set; } 
    public int ReportCode { get; set; } // Can we associate on this field 
    public virtual ICollection<RunStat> RunStats { get; set; } 
} 

public class RunStat 
{ 
    [Key] 
    public int RunStatKey { get; set; } 
    public int ReportCode { get; set; } 
    public DateTime RunDate { get; set; } 
} 

基本上我想用流利的API來配置EF認爲Report.ReportCode是ForeignKey的和RunStat.ReportCode是的PrimaryKey。

回答

10

這是不可能的。 EF中的關係遵循與數據庫中完全相同的規則。這意味着主體表必須具有獨立標識符,該標識符由從屬表引用。在數據庫的情況下,標識符可以是主表的主鍵或唯一列。否則它不是有效的關係。

實體框架不支持唯一鍵。如果要在ReportRunStat之間建立一對多關係,則從屬表(RunStat)必須包含值爲Report.ReportKey的列。沒有其他方法可以使它自動化 - 否則,只需將它定製爲自定義屬性,並在需要時從實體框架手動填充它。

+1

投票將此添加爲實體框架中的新功能http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1050579-unique-constraint-ie-candidate-key-支持 – Brian

相關問題