【问题标题】:EF one to one relationship, the property cannot be configuredEF一对一关系,属性无法配置
【发布时间】:2017-06-06 23:10:19
【问题描述】:

一个申请人有一个通知,一个通知有一个申请人。

我正在尝试在 EF 中实现此功能,但收到以下错误:

"属性 'ApplicantID' 不能配置为导航 财产。该属性必须是有效的实体类型,并且该属性 应该有一个非抽象的 getter 和 setter。供收藏 类型必须实现 ICollection 的属性,其中 T 是有效的 实体类型。”

不确定,我做错了什么。

申请人

[Index]
[Key]
public int ApplicantID { get; set; }
public string ApplicantTitle { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Address { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Address3 { get; set; }
public string Postcode { get; set; }
//fk
public int ApplicantNotificationID { get; set; }
public ApplicantNotification Notification { get; set; }

申请人通知

        [Index]
        public int ApplicantNotificationID { get; set; }
        public bool FirstNotification { get; set; }
        public bool SecondtNotification { get; set; }
        public bool ThirdNotification { get; set; }
        public bool FinalNotification { get; set; }
        public DateTime ReminderDate { get; set; }
        public int ReminderFrequency { get; set; }
        [DataType(DataType.Date)]
        public DateTime FirstNotificationDate { get; set; }
        [DataType(DataType.Date)]
        public DateTime SecondNotificationDate { get; set; }
        [DataType(DataType.Date)]
        public DateTime ThirdNotificationDate { get; set; }
        public bool IsArchive { get; set; }
        //FK
        public int ApplicantID { get; set; }

        //navigation property
        public Applicant Applicant { get; set; }

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    该错误源于第二个表定义中缺少ForeignKeyAttribute 注释,即使每个表都有其他表的导航属性。尝试在ApplicantNotification 上设置外键属性,并将两个表上的导航属性标记为virtual,如下所示:

    [Table("Applicant")]
    public class Applicant
    {
        [Index]
        [Key]
        public int ApplicantID { get; set; }
    
        // other properties
    
        public virtual ApplicantNotification Notification { get; set; }
    }
    
    
    [Table("ApplicantNotification")]
    public class ApplicantNotification
    {
        [Index]
        [Key, ForeignKey("Applicant")]
        public int ApplicantNotificationID { get; set; }
    
        // other properties
    
        public virtual Applicant Applicant { get; set; }
    }
    

    一对一关系的目的是Applicant 可以在有或没有ApplicantNotification 的情况下保存,但ApplicantNotification 在保存时需要Applicant 存在(来自tutorial)。

    类似问题:

    Entity framework Code First One-to-One relationship

    【讨论】:

    • 我的第一个方法确实在申请人 ID 上有 fk 属性,但是这不起作用并重复了同样的错误。然而,这确实有效,奇怪
    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 2015-07-23
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多