Entity Framework Core creating model from existing

2020-02-17 09:32发布

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?

5条回答
三岁会撩人
2楼-- · 2020-02-17 09:57

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楼-- · 2020-02-17 10:01

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

查看更多
小情绪 Triste *
4楼-- · 2020-02-17 10:04

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.

查看更多
冷血范
5楼-- · 2020-02-17 10:11

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

查看更多
Luminary・发光体
6楼-- · 2020-02-17 10: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.

查看更多
登录 后发表回答