How to create a compound (primary) key when using classes as relationships

c# entity-framework-core

Question

If I have:

class Checklist {
   [Key]
   public int ChecklistID {get;set;}
   public string Name {get;set;}
}

class ChecklistItem {
   [Key]
   public int ChecklistItemID {get;set;}
   public string Name {get;set;}
}

class ChecklistAndItem {
   public ChecklistItem ChecklistItem {get;set;}
   public Checklist Checklist {get;set;}
   String description {get;set;}
}

And I want to make a table that has mappings from the ChecklistItemID and ChecklistID used as a composite primary key. This will help me prevent duplicats.

What would the correct mapping be in OnModelCreating() ?

I've tried :

protected override void OnModelCreating(ModelBuilder modelBuilder) {

    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<ChecklistAndItem>()
        .HasKey(table => new {table.Checklist.ChecklistID,table.ChecklistItem.ChecklistItemID}
    );
}

but that gives me this error:

The properties expression
'table => new <>f__AnonymousType0'2( ChecklistID = table.Checklist.ChecklistID, ChecklistItemID = table.ChecklistItem.ChecklistItemID )' is not valid.
The expression should represent a property access: 't => t.MyProperty'.
When specifying multiple properties use an anonymous type:
't => new { t.MyProperty1, t.MyProperty2 }'.
Parameter name: propertyAccessExpression

1
3
3/5/2018 12:53:43 PM

Accepted Answer

This wasn't possible in EF6. Fortunately EF Core allows you to use shadow properties in PK (in addition to FK).

All you need is to make sure the shadow properties are explicitly defined and then use HasKey overload with params string[] propertyNames:

modelBuilder.Entity<ChecklistAndItem>()
    .Property<int>("ChecklistID");

modelBuilder.Entity<ChecklistAndItem>()
    .Property<int>("ChecklistItemID");

modelBuilder.Entity<ChecklistAndItem>()
    .HasKey("ChecklistID", "ChecklistItemID");
4
3/5/2018 1:02:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow