簡體   English   中英

實體框架6表具有許多外鍵,每個外鍵指向不同的表

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM