我正在尝试在表员工和部门之间建立一对零的关系。
public class Staff
{
public int ID { get; set; }
// other fields
[ForeignKey("DepartmentID")]
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
}
public class Department
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public virtual Staff Staff{ get; set; }
}
当我运行这段代码时,它给出了这个错误:
The property 'DepartmentID' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type.
最佳答案
像这样改变你的模型,现在你可以使用 DepartmentID 作为外键
public class Department
{
[Key]
public int DepartmentID { get; set; }
public string Name { get; set; }
public virtual Staff Staff{ get; set; }
}
关于c# - Entity Framework 代码优先一对零关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30185621/