2016-12-05 167 views
0

我有2個模型類:實體框架:外鍵

public class Nurse 
{ 
    public int Id { get; set; } 

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

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

    [Required] 
    public string AddressLine1 { get; set; } 
    [Required] 
    public string AddressLine2 { get; set; } 
    public string AddressLine3 { get; set; } 
    public string AddressLine4 { get; set; } 

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

    [Required] 
    [Phone] 
    public string ContactNumber { get; set; } 

    [Required] 
    public DateTime DateOfBirth { get; set; } 

    [Required] 
    public DateTime RegistrationDate { get; set; } 


    //Foreign Keys 

    public int PaymentId { get; set; } 
    [ForeignKey("PaymentId")] 
    public virtual Payment Payment { get; set; } 


    public int BranchId { get; set; } 
    [Required] 
    [ForeignKey("BranchId")] 
    public virtual Branch Branch { get; set; } 
} // Cls 

public class Payment 
{ 
    public int Id { get; set; } 

    //Type of String instead of to allow for starting zeros 
    [RegularExpression("^[0-9]+$")] 
    public string SortCode { get; set; } 

    [RegularExpression("^[0-9]+$")] 
    public string BankAccountNumber { get; set; } 

    [RegularExpression("^[0-9]+$")] 
    public string ChequeNumber { get; set; } 

    public DateTime DateReceived { get; set; } 

    public string Notes { get; set; } 

    //Foreign Keys 
    public int PaymentTypeId { get; set; } 
    [Required] 
    [ForeignKey("PaymentTypeId")] 
    public PaymentType PaymentType { get; set; } 

    public int NurseId { get; set; } 
    [Required] 
    [ForeignKey("NurseId")] 
    public Nurse Nurse { get; set; } 
} // Cls 

每當我嘗試運行應用程序,我得到以下錯誤:

Exception thrown: 'System.InvalidOperationException' in EntityFramework.dll

Additional information: The ForeignKeyAttribute on property 'Payment' on type 'PNA_Model.Nurse' is not valid. The foreign key name 'PaymentId' was not found on the dependent type 'PNA_Model.Payment'. The Name value should be a comma separated list of foreign key property names.

每付款屬於護士,但不是每個護士都有付款。

如果我支付的「ID」屬性更改爲「PaymentId」錯誤消失,其中根據錯誤信息樣的有道理。

但是我認爲EF很聰明,想出解決辦法本身,我必須與其他類和它們的「身份證」性質類似的情況,我不爲他們收到錯誤消息。

任何想法?

謝謝

+0

您是否嘗試將'ForeignKeyAttribute'添加到'PaymentId'而不是'Payment'? – Mats391

+1

你使用什麼版本的EF? EF6,EF核心? – krillgar

+0

@krillgar Version = 6.0.0.0根據App.config文件 – Shanie

回答

0

好的,我想我發現我做錯了。

首先,實體框架要求,在1對1的關係的依賴(支付)的主鍵還必須是外鍵。

因此,在'護士'類中,我不需要'PaymentId'屬性,因爲在Payment類中,Key(Payment.Id)也將是護士的外鍵,因此將等於護士鍵Nurse.Id)。 在付款類中,我應該刪除'NurseId'屬性,因爲這將在密鑰/外鍵中處理,我可以用兩種方法完成其餘操作。

  1. 支付類 - 上的密鑰(Payment.Id) 使用數據標註

    [ForeignKey("Nurse")] 
    public int Id { get; set; } 
    
  2. 在PaymentConfig類 -

    HasRequired(p => p.Nurse) 
        .WithOptional(n => n.Payment); 
    

第二個選項可能是更好,如果你還想指定

WillCascadeOnDelete(false) 

感謝所有誰幫助!