[英]Set composite key on table with only One-to–Zero-or-One relations
Using EF6 I'm trying to define the following relation A(1)---(0..1)C(0..1)---(1)B
(The (x)
is the cardinality). 我正在尝试使用EF6定义以下关系A(1)---(0..1)C(0..1)---(1)B
( (x)
是基数)。 Table C would then use a composite key of the 2 foreign keys from A and B. 然后,表C将使用A和B中2个外键的组合键。
// Other properties are omitted for brevity
public class A
{
public int Id { get; set; }
public virtual C C { get; set; }
}
public class B
{
public int Id { get; set; }
public virtual C C { get; set; }
}
public class C
{
public virtual A A { get; set; }
public virtual B B { get; set; }
}
This is the fluent API I came up with. 这是我想出的流畅的API。
public class C : EntityTypeConfiguration<C>
{
public C()
{
// Primary Key
this.HasKey(t => new { t.A, t.B}); // This is the problem
// Relationships
this.HasRequired(t => t.A)
.WithOptional(t => t.C);
// cannot use .HasForeignKey
this.HasRequired(t => t.B)
.WithOptional(t => t.C);
// cannot use .HasForeignKey
}
}
HasKey(t => new { tA, tB})
is not allowed and it want a scalar property usually set with .HasForeignKey
. HasKey(t => new { tA, tB})
,并且需要通常使用.HasForeignKey
设置的标量属性。 However since it's a one-to-one I cannot use that. 但是,因为它是一对一的,所以我不能使用它。
What to do? 该怎么办?
When A->C.WithOptional is specified, EF assumes that tables A and C have same PK. 当指定A-> C.WithOptional时,EF假定表A和C具有相同的PK。
I would recommend to keep 0..1 in mind/comments and specify .WithMany().HasForeignKey(..)
in both A->C and B->C links. 我建议记住/注释为0..1,并在A-> C和B-> C链接中都指定.WithMany().HasForeignKey(..)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.