Entity Framework Core creating model from existing database

Dean Kuga picture Dean Kuga · Jan 17, 2017 · Viewed 31.9k times · Source

With Entity Framework Core, how do you generate the EF model and the entities?

According to ASP.NET Core - Existing Database Microsoft article you need to run a command like this one in the Package Manager Console:

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

That gives you zero control on what tables or views to import. Is it possible that this is the only way to reverse engineer the database and create the EF models and entities now with EF Core and how is that progress when compared to the way this was done with full Entity Framework for years now?

Answer

HiHo picture HiHo · Sep 13, 2017

I know this question is a bit old, but I think it's pretty useful for people stumbling over the same problem.

If I've understood your question correctly, you want to specify which Tables should be generated. It should be possible if you add the -Tables Parameter to the command.

Here is the command I used to generate 3 Tables of the Database (in Package-Manager Console):

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=DatabaseName;Trusted_Connection=True;"  
     -Provider Microsoft.EntityFrameworkCore.SqlServer 
     -OutputDir Models -Context NorthwndContext 
     -Tables Products,Categories,Suppliers -Force

As you can see, I use the Northwnd-Database and only generate the tables "Products, Categories and Suppliers". Obviously, you can add more tables, you just have to separate them with commas.

If you don't know, you can get the DatabaseName by going to the Data Connections (Server Explorer), click on the Database you want to add and on the right side (Properties), you see a Property (Name). For me it was "NORTHWND.MDF".

I used -Force to override any Models I've already created.

You can use -DataAnnotations to get annotated models. Otherwise, you get Fluent model configuration.

PS: I've only tried this with ASP.NET Core 2 and Entity Framework Core 2.0.0.