Greg
Greg

Reputation: 1367

EntityFramework - composite foreign key and composite key on the same columns but with different order

I've got a code first class like this:

public class Class1
{
    // first column of primary key, second column of foreign key to class 2
    public string Property1 { get; set; }
    // second column of primary key, first column of foreign key to class 2
    public string Property2 { get; set; }
    public string Property3 { get; set; }
}

public class Class2
{
    // first column of primary key
    public string Property2_1 { get; set; }
    // second column of primary key
    public string Property2_2 { get; set; }
    public string Property2_3 { get; set; }
}

I know it sounds weird, but is it possible to have a primary key on property1 (col 1) and property 2 (col2) and a foreign key on property 2(col 1) and property 1 (col2)? if so, how do I declare it?

Upvotes: 0

Views: 34

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205649

It's perfectly possible with Fluent API (which currently is the only way to configure Composite PK anyway).

First, the PK configuration:

modelBuilder.Entity<Class2>()
    .HasKey(e => new { e.Property2_1, e.Property2_2 });

modelBuilder.Entity<Class1>()
    .HasKey(e => new { e.Property1, e.Property2 });

Then the FK configuration (it's hard to tell exactly the type of the relationship w/o navigation properties, so assuming Class1 (many) <-> (one) Class2):

modelBuilder.Entity<Class1>()
    .HasOne<Class2>()
    .WithMany()
    .HasForeignKey(e => new { e.Property2, e.Property1 });

Just make sure to use the correct Has / With overloads in case you have navigation properties.

Upvotes: 1

Related Questions