我有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很聰明,想出解決辦法本身,我必須與其他類和它們的「身份證」性質類似的情況,我不爲他們收到錯誤消息。
任何想法?
謝謝
您是否嘗試將'ForeignKeyAttribute'添加到'PaymentId'而不是'Payment'? – Mats391
你使用什麼版本的EF? EF6,EF核心? – krillgar
@krillgar Version = 6.0.0.0根據App.config文件 – Shanie