[英]Entity Framework 6 table with many foreign keys each pointing to different tables
我有国家,城市,地区和“帐户地址”表。
我想在“帐户地址”中创建指向国家,城市,地区表的外键列。
我有这段代码,但是在创建数据库时抛出错误
无法将属性\\ u0027Account_Id \\ u0027配置为导航属性。 该属性必须是有效的实体类型,并且该属性应具有非抽象的getter和setter。 对于集合属性,类型必须实现
After New Edit
public class Cities
{
[Key]
public int City_Id { get; set; }
public string City_name { get; set; }
public int Country_Id { get; set; }
[ForeignKey("Country_Id")]
public Countries countries { get; set; }
}
public class Region
{
[Key]
public int Region_Id { get; set; }
public string Region_name { get; set; }
public int City_Id { get; set; }
[ForeignKey("City_Id")]
public Countries countries { get; set; }
}
public class Accounts
{
[Key]
public int Account_Id { get; set; }
public string Fullname { get; set; }
public string Email { get; set; }
public string password { get; set; }
public int Cell_phone { get; set; }
public string Role { get; set; }
public int? estate_office_Id { get; set; }
[ForeignKey("estate_office_Id")]
public Estate_office estate_office { get; set; }
public List<Ads> ads { get; set; }
}
public class Account_address
{
[Key]
public int Id { get; set; }
[ForeignKey("Account_Id"), Column(Order = 0)]
public int Account_Id { get; set; }
[ForeignKey("Country_Id"), Column(Order = 1)]
public int Country_Id { get; set; }
[ForeignKey("City_Id"), Column(Order = 2)]
public int City_Id { get; set; }
[ForeignKey("Region_Id"), Column(Order = 3)]
public int Region_Id { get; set; }
public Accounts accounts { get; set; }
public Countries countries { get; set; }
public Cities cities { get; set; }
public Region region { get; set; }
}
您需要按如下所示在Account_address
上定义public
属性。然后,只有EF知道如何正确映射这些导航属性。
public class Account_address
{
......
......
public Accounts accounts { get; set; } //like this
public Countries countries { get; set; } //like this
public Cities cities { get; set; } //like this
public Region region { get; set; } //like this
}
更新:
因此,您没有对类使用单数命名约定,就遇到了这个问题。要么必须将类的名称更改为单数,要么需要更改如下所示的导航属性名称。您必须对所有这里仅显示了与Accounts
类相关的导航属性。
[ForeignKey("Accounts_Id"), Column(Order = 0)]
public int Accounts_Id { get; set; }
我的建议是遵循基本的命名约定 。然后,您可以避免出现许多上述奇怪的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.