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?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With