2017-03-02 149 views
2

我有兩個表具有複合主鍵:如何創建複合外鍵的表,複合主鍵

public class Event 
{ 
    [Key] 
    [Column(Order = 1)] 
    public string ID1 { get; set; } 

    [Key] 
    [Column(Order = 2)] 
    public int ID2 { get; set; } 
    public DateTime EventDate { get; set; } 
    public string DocID1 { get; set; } 
    public int DocID2 { get; set; } 

}

public class EventDocument 
{ 
    [Key] 
    [Column(Order = 1)] 
    public string ID1 { get; set; } 
    [Key] 
    [Column(Order = 2)] 
    public int ID2 { get; set; } 

    public string Name { get; set; } 
    public string SurName { get; set; } 
    public string Number { get; set; } 

    public virtual ICollection<Event> Events { get; set; } 
} 

我需要創建Event複合外鍵表格到EventDocument表格

我試過像這樣創建FK

類的事件:

[ForeignKey("DocID1")] 
[Column(Order = 0)] 
public string DocID1 { get; set; } 

[ForeignKey("DocID2")] 
[Column(Order = 1)] 
public string DocID2 { get; set; } 

但我得到一個錯誤:

The property 'DocID1' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type."}

我不明白了什麼,我做錯了

回答

5

複合外鍵要求ForeignKey要應用屬性在導航屬性中指定外鍵屬性名稱的逗號分隔列表:

If you add the ForeignKey attribute to a foreign key property, you should specify the name of the associated navigation property. If you add the ForeignKey attribute to a navigation property, you should specify the name of the associated foreign key(s). If a navigation property has multiple foreign keys, use comma to separate the list of foreign key names.

既然你在Event類沒有導航屬性,則應它適用於相應的導航性能在EventDocument類:

[ForeignKey("DocID1, DocID2")] 
public virtual ICollection<Event> Events { get; set; } 

和問題應該得到解決。

但我個人發現與Fluent API建立關係要容易理解,並且不易出錯。舉例來說,同樣可以通過以下流利的配置來實現:

modelBuilder.Entity<EventDocument>() 
    .HasMany(e => e.Events) 
    .WithRequired() // or .WithOptional() 
    .HasForeignKey(e => new { e.DocID1, e.DocID2 }); 

順便說一句相同的複合材料的PK(而不是所有這些Key/Column(Order = ...)屬性):

modelBuilder.Entity<Event>() 
    .HasKey(e => new { e.ID1, e.ID2 }); 

modelBuilder.Entity<EventDocument>() 
    .HasKey(e => new { e.ID1, e.ID2 }); 
+0

什麼明確的答案! !試着接受:)你寫的EventA是什麼意思:「public virtual ICollection Events {get; set;}」 – Songaila

+0

首先我試了1個var。我得到一個錯誤:類型'xxx.Event'屬性'DocID1'上的ForeignKeyAttribute無效。在依賴類型'xxx.Event'上找不到導航屬性「DocID1,DocID2」。名稱值應該是有效的導航屬性名稱。 Goint嘗試Fluent API – Songaila

+0

保持與Fluen API,更容易理解沒有更多的錯誤。謝謝你 – Songaila