2014-02-12 59 views
0

我有一個EF Code First測試應用程序。我想在3個表格之間進行一對多的關聯。我想製作一個看起來像這樣的模式http://gyazo.com/7a1800230a3838adecaafc5cb6676b25.png。當我啓動我的應用程序VS說我:實體框架代碼第一個外鍵問題

的ForeignKeyAttribute上鍵入「ConsoleApplication2.Employee」財產「EducationLevels」是無效的。在依賴類型「ConsoleApplication2.EducationLevel」上找不到外鍵名'EducationLevelId'。名稱值應該是逗號分隔的外鍵屬性名稱列表。

這是我的代碼:

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; } 
} 

回答

1

您需要交換的收集和參考導航性能(一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; } 
} 
+0

就是這樣!乾杯 – BJladu4