EF 4.1 双向一对一问题

本文关键字:一对一 问题 EF | 更新日期: 2023-09-27 17:56:57

嗨,我在使用简单的 EF 4.1 代码优先模型时遇到问题。

我有一个班级的人和一个双向链接的班级调查。数据库模型是正确的,但我总是收到此错误:

Unable to determine the principal end of an association between the types 'DAL.Models.Survey' and 'DAL.Models.Person'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

班级人

[Key]
        public Guid Id { get; set; }
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
        [Required]
        public string Email { get; set; }
        public virtual Survey Survey { get; set; }

班级调查

   [Key]
        public Guid Id { get; set; }
        public bool IsFinished { get; set; }
        public virtual Person Person { get; set; }

数据上下文:

 modelBuilder.Entity<Survey>().HasRequired(s => s.Person).WithOptional().WillCascadeOnDelete(true);

任何人都可以帮忙吗

EF 4.1 双向一对一问题

您应该在映射中定义其他导航属性,因为模型中有它。否则,EF 将创建第二个(一对多)关联:

modelBuilder.Entity<Survey>()
            .HasRequired(s => s.Person)
            .WithOptional(p => p.Survey)
            .WillCascadeOnDelete(true);

我认为您必须通过 HasForeignKey 指定外键属性或使用 Map 指定外键列名称。像这样:

modelBuilder.Entity<Survey>()
    .HasRequired(s => s.Person)
    .WithOptional()
    .WillCascadeOnDelete(true)
    .Map(m => m.MapKey("fk_column"));