2012-12-04 56 views
1

我有兩個模型類:出勤和員工。我已經定義Employee類爲:實體框架Codefirst中的外鍵幫助

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表中它工作正常,但是當我嘗試在考勤表內插入數據會顯示異常。我正在檢查員工並在考勤表中只插入一行員工。

這裏是例外的圖像:

enter image description here

+0

什麼是內部異常(按照主要異常的說明)。另外你如何創建和保存考勤對象? (顯示示例)。 – Umair

回答

2

爲了解決您看到的錯誤(並獲得問題的根源更多細節)的僱員添加一個字段到考勤類,像這樣

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

我不是EF的專家,但是並不是說Attendances集合必須是虛擬的嗎? –

+0

好的,我會試試這個,但這是一對一的關係。我如何做到這一點,如果它是一對一? – Shahnawaz

+0

是的,你是對的...感謝糾正。 –

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

嘗試在您的員工實體上放置關鍵屬性。

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

UPDATE
通過使用沒有參數的WithMany()超載,你可以做一個單一的單向一對多的關係。