EF 4.1双向一对一问题

时间:2011-05-20 12:44:08

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

您好我遇到了一个简单的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; }

的DataContext:

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

任何人都可以帮忙吗

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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