我有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