简体   繁体   English

Entity Framework Core 从现有数据库创建 model

[英]Entity Framework Core creating model from existing database

With Entity Framework Core, how do you generate the EF model and the entities?使用 Entity Framework Core,如何生成 EF model 和实体?

According to ASP.NET Core - Existing Database Microsoft article you need to run a command like this one in the Package Manager Console:根据ASP.NET Core - Existing Database Microsoft 文章,您需要在 Package 管理器控制台中运行如下命令:

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?这是否可能是现在使用 EF Core 对数据库进行逆向工程并创建 EF 模型和实体的唯一方法,与多年来使用完整实体框架完成的方法相比,这种方法有何进展?

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.如果将-Tables参数添加到命令中,则应该是可能的。

Here is the command I used to generate 3 Tables of the Database (in Package-Manager Console):这是我用来生成数据库的 3 个表的命令(在包管理器控制台中):

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".如您所见,我使用 Northwnd-Database 并仅生成“产品、类别和供应商”表。 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).如果您不知道,您可以通过转到数据连接(服务器资源管理器)获取 DatabaseName,单击您要添加的数据库,然后在右侧(属性),您会看到一个属性(名称)。 For me it was "NORTHWND.MDF".对我来说是“NORTHWND.MDF”。

I used -Force to override any Models I've already created.我使用-Force来覆盖我已经创建的任何模型。

You can use -DataAnnotations to get annotated models.您可以使用-DataAnnotations来获取带注释的模型。 Otherwise, you get Fluent model configuration.否则,您将获得 Fluent 模型配置。

PS: I've only tried this with ASP.NET Core 2 and Entity Framework Core 2.0.0. PS:我只在 ASP.NET Core 2 和 Entity Framework Core 2.0.0 上试过这个。

My situation was that I had a .net 4.5+ class library with DbContexts in it.我的情况是我有一个带有 DbContexts 的 .net 4.5+ 类库。

Those DbContexts had been created from an existing DB using the "Code First from existing Database" Wizard.这些 DbContext 是使用“Code First from existing Database”向导从现有数据库创建的。 This Wizard seems to be missing from EF Core. EF Core 中似乎缺少此向导。

To create a new Code First DbContext from an existing DB compatible with EF Core , I loosely followed the guide here要从与 EF Core 兼容的现有数据库创建新的 Code First DbContext ,我大致遵循了此处的指南

My steps:我的步骤:

  • Created a new Core Class Library创建了一个新的核心类库

  • Added the nuget package Microsoft.EntityFrameworkCore添加了 nuget 包Microsoft.EntityFrameworkCore

  • Added the nuget package Microsoft.EntityFrameworkCore.Tools添加了 nuget 包Microsoft.EntityFrameworkCore.Tools
  • Added the nuget package Microsoft.EntityFrameworkCore.SqlServer添加了 nuget 包Microsoft.EntityFrameworkCore.SqlServer
  • Added the nuget package Microsoft.EntityFrameworkCore.SqlServer.Design添加了 nuget 包Microsoft.EntityFrameworkCore.SqlServer.Design

  • Opened the nuget Package Manager console打开 nuget 包管理器控制台

  • 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.请注意,在使用非核心项目时,您可能会遇到 nuget 包管理器控制台的问题。 I avoided this problem by just creating a new Core Class Library, instead of a .net one.我通过创建一个新的核心类库而不是 .net 来避免这个问题。

Once you have created the context, you can edit it like normal in Code First, eg you can delete the tables you don't want to use.创建上下文后,您可以在 Code First 中像往常一样对其进行编辑,例如,您可以删除不想使用的表。

Those who want to convert Sql database schema to EF core using dotnet core follow the steps:那些想要使用 dotnet core 将 Sql 数据库架构转换为 EF core 的人请按照以下步骤操作:

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 :现在,您可以通过应用以下命令轻松生成CRUD代码:

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 folderMyNewController更改为您想要的控制器名称,将ModelName更改为您想要定位的模型文件夹中的模型名称,最后更改 MyDbContext使用 Models 文件夹中可用的系统生成的上下文文件名

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.jsonstartup.cs文件进行了必要的更改

appsettings.json add after the line appsettings.json 在行后添加

"AllowedHosts": "*", "AllowedHosts": "*",

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

startup.cs file add just before the line startup.cs文件在该行之前添加

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

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

Enjoy!!享受!!

There's no way to do that in Entity Framework Core.在 Entity Framework Core 中没有办法做到这一点。 Read the documentation here: https://docs.microsoft.com/en-us/ef/efcore-and-ef6/features在此处阅读文档: https : //docs.microsoft.com/en-us/ef/efcore-and-ef6/features

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.也可以套用骗子的方法:打开VS2015,新建一个与实际项目同名的类库,然后运行实体数据模型向导。

Once your done, copy and paste into your .net core project.完成后,复制并粘贴到您的 .net 核心项目中。 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.但是,运行上面的脚手架命令是一个更好的解决方案。

Scaffold DbContext from existing MS SQL database来自现有 MS SQL 数据库的脚手架 DbContext

Was facing issue in VS 2022 and do.net7 and below solution is worked for me在 VS 2022 和 do.net7 中面临问题,以下解决方案对我有用

  1. Install below 4 packages in API/MVC/WEB/Console application and rebuild application在 API/MVC/WEB/Console 应用程序中安装以下 4 个包并重建应用程序

    Microsoft.EntityFrameworkCore.Design --version 7.0 Microsoft.EntityFrameworkCore.Design——版本 7.0

    Microsoft.EntityFrameworkCore --version 7.0 Microsoft.EntityFrameworkCore——版本 7.0

    Microsoft.EntityFrameworkCore.SqlServer --version 7.0 Microsoft.EntityFrameworkCore.SqlServer——版本 7.0

    Microsoft.EntityFrameworkCore.Tools --version 7.0 Microsoft.EntityFrameworkCore.Tools——版本 7.0

  2. Run below command in Package Mnager Console:在 Package Mnager 控制台中运行以下命令:

    Note : give proper data source, db name, id and pwd in connection string注意:在连接字符串中提供正确的数据源、数据库名称、ID 和密码

    Scaffold-DbContext "Data Source=localhost;Initial Catalog=db_name;Integrated Security=True;TrustServerCertificate=true;User Id=sa;Password=*****" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models脚手架-DbContext“数据源=localhost;初始目录=db_name;集成安全=True;TrustServerCertificate=true;用户ID=sa;密码=*****” Microsoft.EntityFrameworkCore.SqlServer -OutputDir 模型

  3. If any error occurs make sure that 'TrustServerCertificate=true' property present in connection string and restart visual studio and try scaffold command again如果发生任何错误,请确保连接字符串中存在“TrustServerCertificate=true”属性并重新启动 visual studio 并再次尝试脚手架命令

    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我尝试了第 1) 点和第 2) 点的多次尝试,但都失败了,但是当我应用第 3) 点时,它也对我有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Entity Framework Core - 从现有数据库创建模型后尝试添加迁移时出错 - Entity Framework Core - Error when trying to Add Migration after creating Model from existing database 从Entity Framework中的现有表创建模型 - Creating model from existing table in Entity Framework Entity Framework Core - 从 TableName 创建动态 DbSet 模型 - Entity Framework Core - Creating a dynamic DbSet Model from TableName 基于ASP.NET Core中的现有数据库创建实体框架模型 - Create Entity Framework model based on an existing database in ASP.NET Core 来自模型的Entity Framework数据库 - Entity Framework database from a model 以编程方式创建连接字符串以将Entity Framework Code-First模型与现有Sql Azure联合数据库进行映射 - Programmatically creating a connection string for mapping an Entity Framework Code-First model with an existing Sql Azure federation database 使用带有现有子实体的实体框架在数据库中创建实体时出现问题 - Problem creating an entity in the database using Entity Framework with existing child entities 实体框架6从现有表创建模型 - Entity Framework 6 Create model from existing table 当我从现有数据库创建模型时,Entity Framework 4.0 生成只读模型 - Entity Framework 4.0 generating read only model when I create model from existing database 实体框架:现有数据库-&gt;数据模型-&gt;新数据库 - Entity Framework: existing database -> data model -> new database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM