user2102611
user2102611

Reputation:

Can you declare a composite primary key using DbModelBuilder?

I have a table in my database with a composite primary key composed of foo and bar. If I do

private static void EfMapMyTableAdded(DbModelBuilder modelBuilder)
{
     var myTableEntity = modelBuilder.Entity<MyTable>();
     myTableEntity.ToTable("myTable");
     myTableEntity.HasKey(f => f.foo)
         .Property(f => f.foo)
         .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}

and have

foo bar val
1   1   5
1   2   6

and I update the first record with a value of 7 it will also update the second record. But if I use

private static void EfMapMyTableAdded(DbModelBuilder modelBuilder)
{
     var myTableEntity = modelBuilder.Entity<MyTable>();
     myTableEntity.ToTable("myTable");
     myTableEntity.HasKey(f => f.foo)
         .Property(f => f.foo)
         .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
     myTableEntity.HasKey(b => b.bar)
         .Property(b => b.bar)
         .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}

it updates only updates the first row, which is what I want. Is this an acceptable way of dealing with composite primary keys in EF?

Upvotes: 3

Views: 366

Answers (1)

Alexander Derck
Alexander Derck

Reputation: 14498

To declare a composite key you need to use anonymous projection:

myTableEntity.HasKey(f => new { f.foo, f.bar});

The order of the keys will be in the order you define them, so foo would be order=0 here and bar would be order=1.

Another option is using data annotations:

public class myTableEntity
{   
    [Key, Column(Order=0)]
    public int foo {get; set;}

    [Key, Column(Order=1)]
    public int bar {get; set;}
}

Upvotes: 1

Related Questions