2011-09-29 91 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

对不起 - 编辑我的答案 - 希望它有帮助。 –