我有两个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的外键属性不是 有效
帮我找出命名外键的方法。
答案 0 :(得分:1)
如果Employee有一个指向Department的外键属性,那么Employee不能有多个Departments。因此,将导航属性更改为:
[ForeignKey("DeptId")]
public virtual Department Department { get; set; }