我有国家,城市,地区和"帐户地址"表。
我想在"帐户地址"中创建外键列。指向国家,城市,地区表。
我有这段代码但是在创建数据库时会抛出错误
属性\ u0027Account_Id \ u0027无法配置为 导航属性。该属性必须是有效的实体类型和 property应该有一个非抽象的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; }
}
答案 0 :(得分:2)
您需要在public
类上定义Account_address
属性,如下所示。然后,只有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; }
我的建议是遵循基本命名约定。然后您可以避免上述类似的奇怪错误。