2011-09-29 101 views
12

我的模型:EF-代碼首先複雜類型的導航性能

public class Country 
{ 
    public int CountryId { get; set; } 
    public string Name { get; set; } 

    public virtual ICollection<User> Users { get; set; } 
} 

public class Location 
{ 
    public string Address { get; set; } 

    public virtual int CountryId { get; set; } 
    public virtual Country Country { get; set; } 
}  

public class User{ 

    protected User() 
    { 
     Location = new Location(); 
    } 

    public int UserId { get; set; } 
    public Location Location { get; set; } 

} 

當生成數據庫,我得到:

One or more validation errors were detected during model generation: 

System.Data.Edm.EdmEntityType: : EntityType 'Location' has no key defined. Define the key for this EntityType. 
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �Locations� is based on type �Location� that has no keys defined. 

如何我有一個複雜型內航行的財產?如果我刪除國家航行財產,它工作正常。

回答

10

不支持複雜類型的導航屬性(引用其他實體)。您必須將Location作爲實體(使用自己的表格)或從Location中刪除導航屬性Country(並添加Steve Morgan所述的[ComplexType]屬性)。

編輯

參考:http://msdn.microsoft.com/en-us/library/bb738472.aspx

「複雜型不能包含導航屬性」。

+0

但是'LocationID'類裏的'CountryID'整數怎麼樣?是否有可能使外鍵約束? (我有類似的問題,不能讓它工作) –

+0

@伊薩克:不,這是不可能的。如果你想在數據庫中使用FK,你必須直接在數據庫中執行它,但是EF不會反映它。 –

+1

直接在MSDN的複雜類型描述中提到了這種不支持的事實:http://msdn.microsoft.com/en-us/library/bb738472.aspx –

3

EF想要推斷位置的主鍵,但不能。

public int LocationId { get; set; }添加到Location類,它應該很高興。

如果要使用Location作爲複雜類型,請使用[ComplexType]屬性爲其註釋。

+0

這將生成一個全新的表格。我希望它是一個複雜的類型。 –

+0

對不起 - 編輯我的答案 - 希望它有幫助。 –