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

标签 c# .net entity-framework ef-code-first

我有两个模型类:出勤和员工。我将 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 表时它显示异常。我正在正确检查员工并在出勤表中只插入一行员工。

这是异常的图像:

enter image description here

最佳答案

为了解决您看到的错误(并获得有关根本问题的更多详细信息),将 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;}
}

关于c# - Entity Framework Code First 中的外键帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13705689/

相关文章:

c# - 以编程方式分离 SQL Server 数据库以复制 mdf 文件

c# - 字符串格式数字以百万、千为单位四舍五入

c# - .NET 中事件的返回类型是什么?

c# - PayPal 快速结帐在 MVC .net 中以 html 形式返回响应

c# - 从代码中使用 EntityFramework 重构数据库

c# - 事件没有被解雇

c# - 为什么visual studio默认检测到的Mac Agent无法连接到mac agent?

c# - 在 EF Core 中过滤 "include"实体

c# - 使用继承时设置外键关联的正确方法

c# - 将 linq 转换为模型类失败 "Unable to cast object of type ' System.Data.Entity.Infrastruct.DbQuery`1"