实体框架代码第一外键问题

时间:2014-02-12 22:36:35

标签: c# sql-server entity-framework ef-code-first

我有一个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; }
}

1 个答案:

答案 0 :(得分: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; }
}