Skip to main content
 首页 » 编程设计

c#之Entity Framework Code First 中的外键帮助

2024年02月20日10bluestorm

我有两个模型类:出勤和员工。我将 Employee 类定义为:

public class Employee 
{ 
    public int Id { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 
} 

然后我将 Attendance 类定义为:

public class Attendance 
{ 
    public int Id { get; set; } 
    public Employee Employee { get; set; } //This is the foreign key 
    public DateTime LoginDate { get; set; } 
    public DateTime LogoutDate { get; set; } 
} 

当我尝试将数据插入 Employee 表时它工作正常,但是当我尝试将数据插入 Attendance 表时它显示异常。我正在正确检查员工并在出勤表中只插入一行员工。

这是异常的图像:

请您参考如下方法:

为了解决您看到的错误(并获得有关根本问题的更多详细信息),将 EmployeeId 字段添加到 Attendance 类中,如下所示

public class Attendance 
{ 
    public int Id { get; set; } 
    //This exposes the foreign key on attendance 
    public int EmployeeId {get; set;} 
    public Employee Employee { get; set; } //This is the foreign key 
    public DateTime LoginDate { get; set; } 
    public DateTime LogoutDate { get; set; } 
} 

真正的问题(我相信)是 EF 无法确定关系的所有者。如果没有更多信息,它无法确定 Attendance 与 Employee 的关系是多对一还是一对一。一个简单的解决方案(我假设它是多对一的关系)是像这样将 Attendance 对象的集合添加到 Employee 类中

public class Employee 
{ 
    public int Id { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 
    public virtual ICollection<Attendance> Attendances {get; protected set;} 
}