![](/img/trans.png)
[英]Entity Framework 5 codefirst / Required and optional foreign key relations are null
[英]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.