实体框架代码中的外键帮助

时间:2012-12-04 14:55:50

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

我有两个Model类:出勤和员工。我已将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; }
}

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

以下是例外情况的图片:

enter image description here

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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()重载,您可以建立一个单向的单向关系。

答案 2 :(得分: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; }
}

答案 3 :(得分:0)

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