Search code examples
sql-serverentity-frameworkentity-framework-6composite-primary-keyef-database-first

Entity Framework 6 Database First Doesn't Generate Entity on Table With Composite Key


Suppose I have the following table definition with a composite primary key:

create table [dbo].[CustomerRequests] (
    [CustomerId] int not null,
    [RequestId] int not null,
    constraint [PK_CustomerRequests] primary key clustered ([CustomerId] asc, [RequestId] asc),
    constraint [FK_CustomerRequests_Customers] foreign key ([CustomerId]) references [dbo].[Customers] ([CustomerId]),
    constraint [FK_CustomerRequests_Requests] foreign key ([RequestId]) references [dbo].[Requests] ([RequestId])
);

When I update the model to include this table, Entity Framework fails to generate the entity class. Is this due to the composite primary key? Is there any way to make Entity Framework generate the entity class?


Solution

  • Gert Arnold's comment pointed me in the right direction, as did this answer.

    Once I added another column besides the two primary keys, Entity Framework generated the entity. Here is a sample table definition for which EF Database First will create an entity:

    create table [dbo].[CustomerRequests] (
        [CustomerId] int not null,
        [RequestId] int not null,
        [TimestampUtc] datetime not null,
        constraint [PK_CustomerRequests] primary key clustered ([CustomerId] asc, [RequestId] asc),
        constraint [FK_CustomerRequests_Customers] foreign key ([CustomerId]) references [dbo].[Customers] ([CustomerId]),
        constraint [FK_CustomerRequests_Requests] foreign key ([RequestId]) references [dbo].[Requests] ([RequestId])
    );