2011-02-28 140 views
2

我正在與EF代碼第一個庫試圖在預約調度應用程序上工作。EF代碼第一個外鍵的

該模型的我都將是一個客戶端,約會,AppointmentType ...

基本上每一個客戶都能擁有一組約會,每個約會可以有一個AppointmentType ...

的代碼如下:

public class Client 
{ 
     [ScaffoldColumn(false)] 
     public int ClientID { get; set; } 

     [Required] 
     public string FirstName { get; set; } 

     [Required] 
     public string LastName { get; set; } 

     [EmailAddress] 
     [Required] 
     public string Email { get; set; } 

     [DataType("DateTime")] 
     public DateTime Birthday { get; set; } 

     [Required] 
     public string CellPhone { get; set; } 

     public string HomePhone { get; set; } 
     public string Notes { get; set; } 

     public virtual ICollection<Appointment> Appointments{ get; set; } 

     public string Name { 
      get{ 
       return FirstName + " " + LastName; 
      } 
     } 
public class Appointment 
{ 
     [ScaffoldColumn(false)] 
     public int AppointmentID { get; set; } 

     [ScaffoldColumn(false)] 
     public int ClientID { get; set; } 

     [ScaffoldColumn(false)] 
     public int AppointmentTypeID { get; set; } 

     [Required] 
     public DateTime AppointmentDate { get; set; } 
     public string Notes { get; set; } 

     public virtual AppointmentType AppointmentType { get; set; } 
     public virtual Client Client { get; set; } 
} 
    public class AppointmentType 
{ 
     [ScaffoldColumn(false)] 
     public int AppointmentTypeID { get; set; } 

     [Required] 
     public string Name { get; set; } 
     public string Description { get; set; } 

     public virtual Appointment Appointment { get; set; } 
} 

一切運作良好時,我創建約會類型和客戶端,但是當我創建約會,我得到以下錯誤...

  • InnerException {「INSERT語句與FOREIGN KEY約束」Appointment_Client \「發生衝突。衝突發生在數據庫\「Salon.Models.SalonContext \」,表\「dbo.Clients \」,列'ClientID'。\ r \ n語句已被終止。「} System.Exception {System.Data.SqlClient。 SQLEXCEPTION}

如果需要更多的詳細信息,請讓我知道......我只是想弄清楚,如果我缺少的任何設置。

enter image description here

enter image description here

這是當我在帖子上進行調試以創建約會時發生的事情... Al l ID的值爲0,這是正確的,但其他字段不能爲空?或者是否重要......只是不太瞭解事情應該如何看待這是我的第一個EF Code First項目......

+0

一切都是例外。顯示你的數據庫模式,異常說明外鍵約束有衝突。 – 2011-02-28 04:01:52

+0

該屏幕截圖有幫助嗎? – jcreamer898 2011-02-28 04:06:13

+0

當您創建新的約會時,ClientID爲空?可能會引發異常 – 2011-02-28 04:08:04

回答

1

根據您的設置,一個AppointmentType只能有一個約會。這是一對一的映射。在這種情況下,最好將AppointmentType移動到約會實體中。否則,我認爲更合乎邏輯,AppoitmentType可以有許多約會,但一個約會只能有一個AppointmentType。因此,您應該在AppointmentType實體內部有一個虛擬ICollection。

public class AppointmentType 
{ 
     [ScaffoldColumn(false)] 
     public int AppointmentTypeID { get; set; } 

     [Required] 
     public string Name { get; set; } 
     public string Description { get; set; } 

     public virtual ICollection<Appointment> Appointments { get; set; } 
} 

我不確定這是什麼原因引起的問題,但它可能是。有時候映射錯誤會導致一些奇怪的異常被拋出。嘗試一下,讓我知道你的問題是否得到解決。

0

通過您的約束AppointmentType和Client不能在約會中爲空。您可以刪除約束或在對象屬性中設置正確的對象。例如,創建客戶端和AppointmentType,然後使用創建的約會類型爲創建的客戶端創建約會。