MySql Scaffolding an Existing Database in EF Core
Posted on 2018-11-10 23:57 火冰·瓶 阅读(115) 评论(0) 编辑 收藏 举报官方文档详见:https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework-core-scaffold-example.html
Scaffolding a Database Using Package Manager Console in Visual Studio
-
Open Visual Studio and create a new Console App (.NET Core) for C#.
-
Add the MySQL NuGet package for EF Core using the
Install-Package MySql.Data.EntityFrameworkCore -Version 8.0.13
NoteThe version (for example,
-v 8.0.13
) must match the actual Connector/NET version you are using. For current version information, seeTable 9.2, “Supported versions of Entity Framework Core”. -
Install the following NuGet packages by selecting either
-
Microsoft.EntityFrameworkCore.Design
EF Core 1.1 only: Also add the
MySql.Data.EntityFrameworkCore.Design
package. -
Microsoft.EntityFrameworkCore.Tools version 1.1.6
(for EF Core 1.1) andMicrosoft.EntityFrameworkCore.Tools version 2.0.3
(for EF Core 2.0)NoteThe .NET tools are included in the .NET Core 2.1 SDK and not required or supported for EF Core 2.1. If this is an upgrade, remove the reference to that package from the .
csproj
file (version 2.0.3 in this example) :<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3" />
-
-
Open
Scaffold-DbContext "server=localhost;port=3306;user=root;password=mypass;database=sakila" MySql.Data.EntityFrameworkCore -OutputDir sakila -f
Visual Studio creates a new
sakila
folder inside the project, which contains all the tables mapped to entities and thesakilaContext.cs
file.
================================================================================================================
.net core 6.0版本略有不同,6.0版本参考如下:
1.安装如下三个包:
MySql.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design
2.在程序包管理控制台运行如下代码:
Scaffold-DbContext -Force -UseDatabaseNames "server=localhost;port=3306;user=root;password=password;database=db_name" MySql.EntityFrameworkCore -OutputDir ProjectName -Context NameMySqlDbContext
//-Force 强制覆盖之前的文件
//-UseDatabaseNames 保留数据库表的名称格式,不填则表名全部自动转化为首字母大写格式
//-OutputDir 输出文件的文件夹,不填则位根目录
//-Context 指定生成的DbContext类的名称,不填则位系统根据数据库名称自动创建
注意事项:
1.程序包管理控制台那里默认项目需要选择指定的类库,否则就是默认的类库
2.如果解决方案种有多个类库,生成数据库models的类库必须是启动类库,或者被启动类库引用