我在 FluentAPI 中连接两个表时遇到问题。它实际上是 FluentAPI 和 Data Annotations 的混合体。我看着这个问题,但它没有帮助我。我尝试使用Index
, 组成的唯一键。
基本上Foo
是主表。Bar
表是可选的。它们通过两列连接。key1
并且key2
对是独一无二的。把它想象成一个父子关系,一个父母只能有一个孩子:
数据实体如下所示:
[Table("foo")]
public class Foo
{
[Key]
[Column("pk", TypeName = "int")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int FooId { get; set; }
[Column("key1", TypeName = "int")]
public int Key1 { get; set; }
[Column("key2", TypeName = "int")]
public int Key2 { get; set; }
public Bar Bar { get; set; }
}
[Table("bar")]
public class Bar
{
[Key]
[Column("key1", TypeName = "int", Order = 1)]
public int Key1 { get; set; }
[Key]
[Column("key2", TypeName = "int", Order = 2)]
public int Key2 { get; set; }
public Foo Foo { get; set; }
}
这是我尝试连接它们的方式:
modelBuilder.Entity<Bar>().HasRequired(p => p.Foo).WithOptional(p => p.Bar);
怎么了?
Bar
确实需要Foo
. Foo
有可选Bar
的 . <--- 这应该是完全足够的,因为Foo
列的名称与Bar
. 但它不起作用。
所以我尝试指定外键:
modelBuilder.Entity<Bar>().HasRequired(p => p.Foo).WithOptional(p => p.Bar).Map(p => p.MapKey(new[] { "key1", "key2" }));
它说:
“指定的列数必须与主键列数匹配”
哇?如何?怎么来的?呃..
我也试过:
modelBuilder.Entity<Bar>().HasIndex(table => new { table.Key1, table.Key2 });
所以我的问题是:
为什么我的解决方案不起作用?我确实指定了复杂的密钥
我怎么能爱它?