47

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?

Phuc Thai
  • 718
  • 7
  • 17
Dean Kuga
  • 11,878
  • 8
  • 54
  • 108
  • Part of your question answers your main question: "How do you generate..[...]" - you pasted it in your question. There was an existing VS extension called Entity Framework Power Tools, but it looks like it's not been updated to work with EF Core yet. Which convention are you used to that lets you pick which objects you want generated? – Mark C. Jan 17 '17 at 19:28
  • @MarkC. With full Entity Framework you are presented with a list of database objects you can select from when you create a new Entity Data Model (edmx file). – Dean Kuga Jan 17 '17 at 19:37
  • Add the tables argument (from https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db ) – Michael Freidgeim Nov 05 '17 at 20:35
  • Does this answer your question? [Can we Scaffold DbContext from selected tables of an existing database](https://stackoverflow.com/questions/39065769/can-we-scaffold-dbcontext-from-selected-tables-of-an-existing-database) – Michael Freidgeim Dec 03 '20 at 18:55

6 Answers6

77

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.

Jawand Singh
  • 1,929
  • 1
  • 24
  • 21
  • 27
    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 '17 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 04 '17 at 00: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. (https://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 06 '17 at 03:55
14

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!!

Manoj Roy
  • 317
  • 2
  • 6
  • 1
    `dotnet ef dbcontext scaffold "Server=;Database=;User Id=;Password=" Microsoft.EntityFrameworkCore.SqlServer -o Models` worked for me. Curious as to why this got a down vote? – rstackhouse Jun 21 '19 at 19:45
  • The final command `dotnet ef...` command failed. Found help [here](https://stackoverflow.com/a/57070108/1521988) – blackboxlogic Feb 01 '23 at 21:25
12

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.

BautaBear
  • 394
  • 3
  • 9
  • 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 '17 at 09: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 '17 at 04: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

Sol W
  • 110
  • 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 '17 at 19:41
  • 5
    Actually you have control over the imported tables, take a look at the Scaffold-dbContext documentation : https://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 : https://github.com/aspnet/EntityFramework/wiki/Design-Meeting-Notes-(October-1,-2015)#table-selection-in-reverse-engineering – Bouam Mar 07 '17 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 '17 at 14:28
  • What if you want to import a SQL server view, not a table? #micdrop – Fandango68 Apr 04 '22 at 04: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.

Greg Gum
  • 33,478
  • 39
  • 162
  • 233
-1

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

Dnyneshwar
  • 728
  • 8
  • 10