在EF 6中尝试使用一对多关系时,外键属性无效

时间:2017-09-14 12:55:34

标签: c# entity-framework entity-framework-6

我有两个POCO课程 雇员

public class Employee
{
    public Employee()
    {
     Departments = new HashSet<Department>();
    }

[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int EmployeeId { get; set; }

public String EmployeeName { get; set; }

public int DeptId { get; set; }

[ForeignKey("DeptId")]
public  ICollection<Department> Departments { get; set; }

}

系类

public class Department
    {      
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int DepartmentId { get; set; }
        public String Name { get; set; }
        public ICollection<Employee> Employees { get; set; }
     }

我想在Emp-Department中将外键命名为默认EF命名约定以外的一对多关系。所以我使用了ForeignKey中的Employee属性。但我得到了例外

  

类型Employee上属性Departments的外键属性不是   有效

帮我找出命名外键的方法。

1 个答案:

答案 0 :(得分:1)

如果Employee有一个指向Department的外键属性,那么Employee不能有多个Departments。因此,将导航属性更改为:

[ForeignKey("DeptId")]
public virtual Department Department { get; set; }