2016-12-05 169 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) 

感谢所有谁帮助!