2011-11-02 61 views
2

我正在使用現有數據庫上的POCO實體模型。 的表具有鍵指向複合鍵的外鍵

public class Table1 
{ 
    [Key] 
    public virtual int Key1 {get; set;} 

    [Key] 
    public virtual int Key2 {get; set;} 

    public virtual ICollection<Table2> Tables2 {get; set;} 

    //more properties here... 
}

的化合物,並與沒有主密鑰的第二表,但2個屬性引用表1的化合物鍵。

public class Table2 
{ 
    public virtual int Key1 {get; set;} 

    public virtual int Key2 {get; set;} 

    [InverseProperty("Tables2")] 
    public virtual Table1 Table1 {get; set;} 

    //more properties here... 
}

問題可以使用地圖這DataAnnotations協會? 如果是這樣,怎麼樣?

+0

用於EF具有如此多屬性的實體是POCO? –

回答

3

是的,你可以定義數據註解該化合物外鍵:

public class Table2 
{ 
    [ForeignKey("Table1"), Column(Order = 1)] 
    public virtual int Key1 {get; set;} 

    [ForeignKey("Table1"), Column(Order = 2)] 
    public virtual int Key2 {get; set;} 

    [InverseProperty("Tables2")] 
    public virtual Table1 Table1 {get; set;} 

    //more properties here... 
} 

或者:

public class Table2 
{ 
    public virtual int Key1 {get; set;} 

    public virtual int Key2 {get; set;} 

    [InverseProperty("Tables2")] 
    [ForeignKey("Key1, Key2")] 
    public virtual Table1 Table1 {get; set;} 

    //more properties here... 
} 

但真正的問題是,你的Table2具有通過不需要主鍵實體框架。我不認爲有任何解決方法可以解決此問題 - 除了向表中添加主鍵之外。

+0

謝謝!這是我正在尋找的。我正在與DBA一起工作來獲得這張表。 –