Entity Framework Core creating model from existing database
My situation was that I had a .net 4.5+ class library with DbContexts in it.
Those DbContexts had been created from an existing DB using the "Code First from existing Database" Wizard. This Wizard seems to be missing from EF Core.
To create a new Code First DbContext from an existing DB compatible with EF Core, I loosely followed the guide here
My steps:
Created a new Core Class Library
Added the nuget package Microsoft.EntityFrameworkCore
- Added the nuget package Microsoft.EntityFrameworkCore.Tools
- Added the nuget package Microsoft.EntityFrameworkCore.SqlServer
Added the nuget package Microsoft.EntityFrameworkCore.SqlServer.Design
Opened the nuget Package Manager console
Entered the command
Scaffold-DbContext "data source=MYSQLDBSERVER\MYSQLINSTANCE;initial catalog=MYDB;integrated security=True;MultipleActiveResultSets=True;"
Entered as provider
Microsoft.EntityFrameworkCore.SqlServer
Please note that when using a non-Core project you might run into problems with the nuget Package Manager console. I avoided this problem by just creating a new Core Class Library, instead of a .net one.
Once you have created the context, you can edit it like normal in Code First, e.g. you can delete the tables you don't want to use.
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.