繁体   English   中英

实体框架Codefirst中的外键帮助

[英]Foreign Key help in Entity Framework Codefirst

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

这是一个异常的图像:

在此输入图像描述

为了解决您看到的错误(并获得有关根问题的更多详细信息),请将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类中,就像这样

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

您需要定义外键属性:

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM