2013-10-16 80 views
0

我有以下实体:如何使用Fluent API将外键正确映射到一对一或一对一的关系?

public class Foo 
{ 
    public int MyId1 { get; set; } 
    public int MyId2 { get; set; } 
    public int MyId3 { get; set; } 
    public Bar Bar { get; set; } 
} 

public class Bar 
{ 
    public int MyId1 { get; set; } 
    public int YourId2 { get; set; } 
    public int MyId3 { get; set; } 
    public Foo Foo { get; set; } 
} 

和映射:

// Foo Mapping 
this.HasKey(t => new { t.MyId1, t.MyId2, t.MyId3 }); 
this.Property(t => t.MyId1).HasColumnName("my_id1"); 
this.Property(t => t.MyId2).HasColumnName("my_id2"); 
this.Property(t => t.MyId3).HasColumnName("my_id3"); 

// Bar Mapping 
this.HasKey(t => new { t.MyId1, t.MyId3, t.YourId2 }); // Notice different order 
this.Property(t => t.MyId1).HasColumnName("my_id1"); 
this.Property(t => t.YourId2).HasColumnName("your_id2"); 
this.Property(t => t.MyId3).HasColumnName("my_id3"); 
this.HasRequired(t => t.Foo) 
    .WithOptional(t => t.Bar); 

当我做了选择上的富,产生的SQL查询看起来是这样的:

select * 
from Foo foo 
left outer join Bar bar 
    on foo.my_id1 = bar.Foo_MyId1 
    and foo.my_id2 = bar.Foo_MyId2 
    and foo.my_id3 = bar.Foo_MyId3 

这显然给我SQL错误。我猜这是因为它试图推断关系中的外键列。于是,我就在映射指定实际FK列名:

this.HasRequired(t => t.Foo) 
    .WithOptional(t => t.Bar) 
    .Map(m => 
    { 
     m.MapKey("my_id1", "your_id2", "my_id3"); 
    } 
); 

但是这给了我以下错误:

Unhandled Exception: System.Data.Entity.ModelConfiguration.ModelValidationException: 
One or more validation errors were detected during model generation: 

my_id1: Name: Each property name in a type must be unique. Property name 'my_id1' is already defined. 
your_id2: Name: Each property name in a type must be unique. Property name 'your_id2' is already defined. 
my_id3: Name: Each property name in a type must be unique. Property name 'my_id3' is already defined. 

不知道如何解决这个问题?

回答

1

.Map(...)用于在未定义POCO中的外键时指定外键的名称。在你的情况下,你可以在你的POCO中定义代表FK的属性,这样你会得到这个重复的名字错误。

我一直无法确定如何去做你正在问的问题(即使用流畅的api为一对一关系指定FK字段),但它可以通过使用[ForeignKey("NavPropertyName"), Column(Order = #)]属性的数据注释来完成

+0

感谢您的回答,但在这种情况下,m没有MapLeftKey或MapRightKey,只有MapKey和ToTable。我正在使用EF 6.0-rc。我认为这些仅在使用WithMany后才可用。任何其他想法? – Yuyo

+0

有趣。在Bar的Foo属性中使用[ForeignKey(“my_id1,your_id2,my_id3”)]似乎已经完成了。现在,肯定有一种方法可以使用Fluent API来实现这一点! – Yuyo

+0

好的,我发现了一些有趣的东西。因此,我正在使用遗留数据库,如果您注意到上面的代码,Bar的PK与Foo的PK的顺序不同。如果我使用具有相同顺序PK的表尝试此操作,HasRequired(...)。WithOptional(...)可以在不需要使用ForeignKey属性的情况下工作。 – Yuyo

相关问题