我的模特:
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.
如何在复杂类型中拥有导航属性?如果我删除国家导航属性,它可以正常工作。
答案 0 :(得分:10)
不支持复杂类型的导航属性(引用其他实体)。您必须使Location
实体(具有自己的表格)或从Country
删除导航属性Location
(并添加Steve Morgan所提及的[ComplexType]
属性)
修改强>
参考:http://msdn.microsoft.com/en-us/library/bb738472.aspx
“复杂类型不能包含导航属性。”
答案 1 :(得分:3)
EF希望推断出位置的主键,但不能。
将public int LocationId { get; set; }
添加到Location
课程,它应该感到高兴。
如果您想将Location
用作复杂类型,请使用[ComplexType]
属性进行注释。