2014-01-28 55 views
1

我有一個組合鍵定義爲一個單獨的類。EntityFramework Fluent API將一個類映射爲一個複合鍵

public class ClassA : Entity 
{ 
    public virtual ClassACompositeKey CompositeKey { get; set; } 
} 

public class ClassACompositeKey 
{ 
    public int ThisId { get; set; } 

    public int ThatId { get; set; } 

    public int OtherId { get; set; } 
} 

難以用流利的api爲實體框架映射。我曾嘗試爲複合類創建複雜類型配置,但沒有運氣。當我嘗試映射爲

this.HasKey(k => new { k.CompositeKey.ThisId, k.CompositeKey.ThatId, k.CompositeKey.OtherId }); 

我得到一個錯誤,指出

屬性表達數k =>新<> f__AnonymousType2(ThisId = k.CompositeKey.ThisId,ThatId = k.CompositeKey .ThatId,OtherId = k.CompositeKey.OtherId)'無效。表達式應該代表一個屬性。

我對EF和Fluent API有點新,所以我甚至不知道這是否可能。任何幫助,將不勝感激。

回答

2

不幸的是它不被支持。關鍵屬性必須具有原始類型(int,long,string,Guid,DateTime等),並且可以直接在實體類中,而沒有圍繞它們的包裝類。所以,你必須定義組合鍵,像這樣:

public class ClassA : Entity 
{ 
    public int ThisId { get; set; } 

    public int ThatId { get; set; } 

    public int OtherId { get; set; } 
} 

...用流利的映射:

this.HasKey(k => new { k.ThisId, k.ThatId, k.OtherId }); 
相關問題