【问题标题】:EF 4.1 Bidirectional one-to-one problemEF 4.1 双向一对一问题
【发布时间】:2011-05-20 12:44:08
【问题描述】:

您好,我在使用简单的 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);

谁能帮忙

【问题讨论】:

    标签: c# model-view-controller entity-framework-4 ef-code-first


    【解决方案1】:

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

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

    【讨论】:

    • @Nealv:嗯,奇怪。我已将您的模型和映射完全复制到一个测试项目中,并且我没有收到错误(即使没有使用您的原始映射代码)。这里也将其描述为有效映射:weblogs.asp.net/manavi/archive/2011/04/14/…SurveyPerson 类上还有其他 Fluent 映射吗?您是从模型创建数据库还是使用现有数据库? (我将从我的答案中删除 CTP5 备注。)
    • @Nealv:你能检查一下你的 Fluent Mapping 的代码是否真的被执行(通过设置一个断点左右)?我刚刚看到,当我没有这种流畅的映射时,我也会收到此错误(这是有道理的,因为不能仅从模型类中确定主体和依赖)。
    • 谢谢!这解决了我的问题!
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多