2
votes

I have a SQL Server Database with many tables created previously that are used by a software. I'm starting a ASP.NET core 2.0 solution to replace the old software and I chose Database First Process with EntityFramework Core to obtain those tables as classes and to generate the Database Context by using Scaffold-DbContext "MY_CONNECTION_STRING" Microsoft.EntityFrameworkCore.SqlServer -outputDir MY_PATH. The imported model classes' primary keys' columns are not decorated with the Key attribute although the imported tables in the SQL Server model browser shows that they have Primary Key (int fields type), also the model builder fluent mapping in the OnModelCreating method of the Database Context is not generating the HasKey function. for example:

Table script:

enter image description here

Model:

enter image description here

Fluent mapping:

enter image description here

As you can see, class property is not decorated with Key attribute nor fluent mapping generated [PK_AccountingAllocations] primary key.

Database has many tables and I would like to import tables including primary keys to the model and fluent mapping, ¿is it possible and how can I achieve it? thanks for your help.

1
Why screenshots for simple text? Just to waste bytes?Sir Rufo
an "Id" property is a PK by convention, there is no need for EF to include any specific data annotation or fluent API mapping for this.DevilSuichiro
Same issue. What should I do if PK has some custom name?Ssss

1 Answers

3
votes

The scaffold-dbcontext command has an option called

-DataAnnotations

that you need to use if you want to see attributes on your model classes. Without that only the fluent Api is used by default.