Search code examples
c#entity-frameworkef-code-firstfluentcomposite-key

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). Table C would then use a composite key of the 2 foreign keys from A and B.

// 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.

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 { t.A, t.B}) is not allowed and it want a scalar property usually set with .HasForeignKey. However since it's a one-to-one I cannot use that.

What to do?


Solution

  • When A->C.WithOptional is specified, EF assumes that tables A and C have same PK.

    I would recommend to keep 0..1 in mind/comments and specify .WithMany().HasForeignKey(..) in both A->C and B->C links.