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.
不知道如何解决这个问题?
感谢您的回答,但在这种情况下,m没有MapLeftKey或MapRightKey,只有MapKey和ToTable。我正在使用EF 6.0-rc。我认为这些仅在使用WithMany后才可用。任何其他想法? – Yuyo
有趣。在Bar的Foo属性中使用[ForeignKey(“my_id1,your_id2,my_id3”)]似乎已经完成了。现在,肯定有一种方法可以使用Fluent API来实现这一点! – Yuyo
好的,我发现了一些有趣的东西。因此,我正在使用遗留数据库,如果您注意到上面的代码,Bar的PK与Foo的PK的顺序不同。如果我使用具有相同顺序PK的表尝试此操作,HasRequired(...)。WithOptional(...)可以在不需要使用ForeignKey属性的情况下工作。 – Yuyo