簡體   English   中英

實體框架代碼第一個外鍵問題

[英]Entity Framework Code First Foreign Key issue

我有一個EF Code First測試應用程序。 我想在3個表之間建立一對多關聯。 我想制作一個看起來像http://gyazo.com/7a1800230a3838adecaafc5cb6676b25.png的架構。 當我啟動我的應用程序時,VS告訴我:

類型“ ConsoleApplication2.Employee”上屬性“ EducationLevels”上的ForeignKeyAttribute無效。 在從屬類型“ ConsoleApplication2.EducationLevel”上找不到外鍵名稱“ EducationLevelId”。 Name值應該是逗號分隔的外鍵屬性名稱列表。

這是我的代碼:

class Program
{
    static void Main(string[] args)
    {
        using (EmployeesContext context = new EmployeesContext())
        {                
            Profession p = new Profession { Id = 0, NameOfProfession = "myprof" };
            context.Profession.Add(p);
            context.SaveChanges();
        }
    }
}

public enum Sex { Man = 0, Woman = 1 }

public class Employee
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public byte Age { get; set; }
    public Sex Sex { get; set; }
    public int EducationLevelId { get; set; }
    public int ProfessionId { get; set; }

    [ForeignKey("EducationLevelId")]
    public virtual ICollection<EducationLevel> EducationLevels { get; set; }
    [ForeignKey("ProfessionId")]
    public virtual ICollection<Profession> Professions { get; set; }
}

public class EducationLevel
{
    [Key]
    public int Id { get; set; }
    public string Level { get; set; }

    public virtual Employee Employees { get; set; }
}

public class Profession
{
    [Key]
    public int Id { get; set; }
    public string NameOfProfession { get; set; }

    public virtual Employee Employees { get; set; }
}

public class EmployeesContext : DbContext
{
    public DbSet<Employee> Employee { get; set; }
    public DbSet<EducationLevel> EducationLevel { get; set; }
    public DbSet<Profession> Profession { get; set; }
}

您需要交換集合和參考導航屬性(一個Employee一個 EducationLevel一個 Profession ,但不多,而EducationLevel許多 Employees而不是一個,而Profession許多 Employees而又沒有一個):

public class Employee
{
    // ...
    public int EducationLevelId { get; set; }
    public int ProfessionId { get; set; }

    [ForeignKey("EducationLevelId")]
    public virtual EducationLevel EducationLevel { get; set; }
    [ForeignKey("ProfessionId")]
    public virtual Profession Profession { get; set; }
}

public class EducationLevel
{
    // ...

    public virtual ICollection<Employee> Employees { get; set; }
}

public class Profession
{
    // ...

    public virtual ICollection<Employee> Employees { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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