1

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

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

然后我将出勤类定义为:

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; }
}

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

这是异常的图像:

在此处输入图像描述

4

4 回答 4

2

您需要定义一个外键属性:

public class Attendance
{
    public int Id { get; set; }
    public int EmployeeID { get; set; }
    public Employee Employee { get; set; }
    public DateTime LoginDate { get; set; }
    public DateTime LogoutDate { get; set; }
}

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

将外键添加为 int 后,您可以对其进行配置:

public class AttendanceConfiguration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<Attendance>
{
    public AttendanceConfiguration()
    {
        this.HasRequired(a => a.Employee)
            .WithMany()
            .HasForeignKey(a => a.EmployeeID);
    }
}

然后在上下文中定义这个配置

public class Context : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new AttendanceConfiguration());
    }
}

更新
通过使用没有参数的 WithMany() 重载,您可以建立一个单向的一对多关系。

于 2012-12-04T15:09:18.583 回答
2

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

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 无法确定关系的所有者。如果没有更多信息,则无法确定出勤与员工的关系是多对一还是一对一。一个简单的解决方案(我假设它是多对一的关系)是像这样将出勤对象的集合添加到 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;}
}
于 2012-12-04T15:03:25.223 回答
0

您需要公开密钥本身,而不仅仅是实体。

public class Attendance
{
    public int Id { get; set; }
    public Employee Employee { get; set; }
    public int EmployeeId { get; set; } // THIS is the foreign key.
    public DateTime LoginDate { get; set; }
    public DateTime LogoutDate { get; set; }
}
于 2012-12-04T15:01:56.457 回答
0

尝试在您的员工实体上放置一个关键属性。

于 2012-12-04T15:03:06.650 回答