3

嗨我有一个简单的EF 4.1代码第一个模型的问题。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); 

谁能帮助请

回答

0

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

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

这是不可能的。 – Nealv 2011-05-20 12:55:53

1

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

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

同样的错误(我正在使用4.1抱歉) – Nealv 2011-05-20 14:17:01

+0

@Nealv:嗯,奇怪。我已经将模型和映射完全复制到一个测试项目中,并且没有发生错误(即使没有使用原始映射代码)。它在这里也被描述为有效的映射:http://weblogs.asp.net/manavi/archive/2011/04/14/associations-in-ef-4-1-code-first-part-3-shared-primary- key-associations.aspx在Survey Survey或Person类中是否有其他Fluent映射?你是从模型创建数据库,还是使用现有的数据库? (我将从我的答案中删除CTP5评论。) – Slauma 2011-05-20 14:51:05

+0

@Nealv:你能否检查一下Fluent Mapping的代码是否真的执行过(通过设置断点等)?我刚刚看到,当我没有这种流畅的映射时,我也会得到这个错误(这是有道理的,因为主体和依赖不能从模型类单独确定)。 – Slauma 2011-05-20 15:55:07