3

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?

Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
  • When I used EF, we created the entities in the code, then used migrations to create the SQL tables. I think it ignores tables that are created manually in SQL. Not totally positive, just want I experienced. – SS_DBA Oct 13 '17 at 18:58
  • 4
    EF creates a many-to-many association with this table invisibly in the middle. If you don't want that, give the table a single surrogate primary key (or any other meaningful field). – Gert Arnold Oct 13 '17 at 19:13

1 Answers1

4

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])
);
Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88