Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaffold-DbContext creating model for table without a primary key

I am trying to create DBcontext and corresponding model for a particular table in ASP.NET core MVC application. This table doesn't have any primary key.

I am running following Scaffold-DbContext command-

Scaffold-DbContext "Server=XXXXX;Database=XXXXXXX;User Id=XXXXXXX;password=XXXXXXX" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -t TABLE_NAME -force -verbose

In Package Manager Console, I can see this verbose output-

...............
...............
Unable to identify the primary key for table 'dbo.TABLE_NAME'.
Unable to generate entity type for table 'dbo.TABLE_NAME'.

My Environment is - VS2015 update3, .NET core 1.0.0, ASP.NET MVC core application.

Is there anyway to create a model for a table without primary key?

like image 636
Sanket Avatar asked Sep 26 '16 10:09

Sanket


People also ask

Can we create table without primary key in Entity Framework?

The Entity framework will not support to have a table without primary key, but we can overcome this issue by accessing the table with additional column via a view and marking the new column as Primary in entity framework. Entity Framework requires primary keys for entities.

Is it possible for an entity to not have a primary key?

Every entity in the data model shall have a primary key whose values uniquely identify entity instances. The primary key attribute cannot be optional (i.e., have null values).

How do you use a table which is not having a primary key in Entity Framework?

The table/view TABLE_NAME does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and uncomment it.

Can we scaffold-DbContext from selected tables of an existing database?

Look at the old answer. It describes that one can use dotnet ef dbcontext scaffold with multiple -t parameters, which specifies the tables which need be scaffolded.


1 Answers

Support for complex types (those that don't have an entity key) in EF Core is on the backlog: https://github.com/aspnet/EntityFramework/issues/246. That's why any attempt to reverse engineer a table without a primary key defined won't work at the moment.

like image 59
Mike Brind Avatar answered Sep 28 '22 05:09

Mike Brind