51

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?

4

6 Answers 6

83

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.

3
  • 28
    Thanks, I just think it's ludicrous to go from full featured edmx UI that allows you too view and edit the tables, relationships, fields and so on to some command line tool and tout that as ground braking progress...
    – Dean Kuga
    Sep 14, 2017 at 14:25
  • 10
    I don't know what crack MS has been on lately. Core solves the problem of running .Net on non IIS servers...a problem by 1% of IT shops that run MS, and if the idea catches on the need for Windows servers wanes...as a business plan I don't get it.
    – infocyde
    Nov 4, 2017 at 0:48
  • 1
    @HiHo I copied your code and ran in the package console nothing happens however earlier the same worked for .net core 1.1 and I recently upgraded to core 2.0 with ef as well and I am unable to update models. (github.com/aspnet/EntityFrameworkCore/wiki/Roadmap) they says We will do our best to complete or at least make good progress on these:
    – Zaker
    Dec 6, 2017 at 3:55
16

Those who want to convert Sql database schema to EF core using dotnet core follow the steps:

Run all the commands one after one (first command for those who want to create a new project else you can ignore that and just run other given commands from your project root folder)

dotnet new mvc -o <ProjectName>

dotnet add package Microsoft.EntityFrameworkCore.SqlServer

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design

dotnet add package Microsoft.EntityFrameworkCore.SqlServer.Design

dotnet add package Microsoft.EntityFrameworkCore.Tools

dotnet tool install --global dotnet-aspnet-codegenerator

Finally...

dotnet ef dbcontext scaffold "Server=servername\instancename;Database=My_Database;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

This will create the necessary models and context of your db schema inside the models folder of your project.

Now easily you can generate CRUD code by applying the following command :

dotnet aspnet-codegenerator controller -name <MyNewController> -m <ModelName> -dc <MyDbContext> --relativeFolderPath Controllers --useDefaultLayout --referenceScriptLibraries 

Change the MyNewController with your desired controller name , ModelName with the model name inside the models folder that you want to target and finally MyDbContext with the system generated context file name available inside the Models folder

but before run that command make sure you have made the necessary changes at your appsettings.json and startup.cs file inside your project folder

appsettings.json add after the line

"AllowedHosts": "*",

 "ConnectionStrings": {
    "MyDbConnection": "Server=servername\\instancename;Database=My_Database;Trusted_Connection=True;"
  }

startup.cs file add just before the line

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

services.AddDbContext<SwiftRbs_LocalContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("MyDbConnection")));

Enjoy!!

2
  • 2
    dotnet ef dbcontext scaffold "Server=<server>;Database=<Database>;User Id=<user>;Password=<password>" Microsoft.EntityFrameworkCore.SqlServer -o Models worked for me. Curious as to why this got a down vote? Jun 21, 2019 at 19:45
  • 1
    The final command dotnet ef... command failed. Found help here Feb 1, 2023 at 21:25
13

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.

2
  • 3
    +1 for creating a new Core Class Library, instead of a .net one. .Net 4.x project throws FileNotFoundException on Microsoft.EntityFrameworkCore.Design
    – Youngjae
    Jul 25, 2017 at 9:18
  • They are all .NET, I think you mean using a .NET Core class library instead of a .NET Framework class library.
    – bcr
    Aug 27, 2017 at 4:54
7

There's no way to do that in Entity Framework Core. Read the documentation here: https://learn.microsoft.com/en-us/ef/efcore-and-ef6/features

4
  • 5
    Wow, there's a lot missing... so why would anyone want to use this crippled ORM called EF Core? Is cross-platform the only advantage/incentive to use EF Core?
    – Dean Kuga
    Jan 17, 2017 at 19:41
  • 5
    Actually you have control over the imported tables, take a look at the Scaffold-dbContext documentation : learn.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell you have the -Tables parameter where you specify all the tables that you want to import, here is an exemple : github.com/aspnet/EntityFramework/wiki/…
    – Bouam K
    Mar 7, 2017 at 15:24
  • 2
    @Bouam Once you go through that do you still get the edmx UI where you can view and edit database objects and fields and see the relationships between your tables?
    – Dean Kuga
    Sep 14, 2017 at 14:28
  • What if you want to import a SQL server view, not a table? #micdrop
    – Fandango68
    Apr 4, 2022 at 4:47
3

You can also apply the cheater's method: Open VS2015, create a new class lib with the same name as the actual project, and then run the Entity Data Model Wizard.

Once your done, copy and paste into your .net core project. There is a bit of tweaking required of the resulting code, but it's trivial.

However, running the scaffold command as above is a better solution.

0

Scaffold DbContext from existing MS SQL database

Was facing issue in VS 2022 and dotnet7 and below solution is worked for me

  1. Install below 4 packages in API/MVC/WEB/Console application and rebuild application

    Microsoft.EntityFrameworkCore.Design --version 7.0

    Microsoft.EntityFrameworkCore --version 7.0

    Microsoft.EntityFrameworkCore.SqlServer --version 7.0

    Microsoft.EntityFrameworkCore.Tools --version 7.0

  2. Run below command in Package Mnager Console:

    Note: give proper data source , db name, id and pwd in connection string

    Scaffold-DbContext "Data Source=localhost;Initial Catalog=db_name;Integrated Security=True;TrustServerCertificate=true;User Id=sa;Password=*****" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

  3. If any error occurs make sure that 'TrustServerCertificate=true' property present in connection string and restart visual studio and try scaffold command again

    I tried multiple attempts by points 1) and 2) but it was failing but when I applied 3) point as well it worked for me

Not the answer you're looking for? Browse other questions tagged or ask your own question.