EF6 时代,可以通过界面操作,添加数据库实体。
EF Core 需要通过 CLI 来进行该操作,具体请参考EF Core官方文档:反向工程。
PMC 工具(仅限 Visual Studio)或 CLI 工具。
核心 NuGet 包:Microsoft.EntityFrameworkCore.Design
还需要为要进行反向工程的数据库架构安装适当的数据库提供程序
dotnet ef dbcontext scaffold "[数据库连接串]" [提供程序]如:
dotnet ef dbcontext scaffold "server=localhost;database=efcore;uid=sa;pwd=Qwe123456;" Microsoft.EntityFrameworkCore.SqlServer上述命令,会生成整个数据库的表,如果需要指定特定的表,需要使用如下:
dotnet ef dbcontext scaffold "[数据库连接串]" [提供程序] --table table_name1 --table table_name2默认情况会修正表/列名,使用该参数尽量保留原名称。
-UseDatabaseNames #PMC--use-database-names #.NET Core CLI默认情况下,使用 Fluent API 配置实体类型。使用下面的命令,可以改为使用数据注释。
-DataAnnotations #PMC--data-annotations #.NET Core CLIFluent API
entity.Property(e => e.Title) .IsRequired() .HasMaxLength(160);数据注释
[Required][StringLength(160)]public string Title { get; set; }指定将生成的 DbContext 类的名称
-Context #PMC--context #.NET Core CLI-ContextDir Data -OutputDir Models #PMC--context-dir Data --output-dir Models #.NET Core CLI-Namespace Your.Namespace -ContextNamespace Your.DbContext.Namespace #PMC--namespace Your.Namespace --context-namespace Your.DbContext.Namespace #.NET Core CLI这里命名为:DbFirstTest
# 引入 EF Core 核心包dotnet add package Microsoft.EntityFrameworkCore.Design -v 6.0.4# 引入 SQL Server 提供程序dotnet add package Microsoft.EntityFrameworkCore.SqlServer -v 6.0.4在执行 Scaffold 命令前,如果使用 vs 打开 shell 一般是在解决方案的目录下,需要先 cd 进入项目目录:
# 如下,我的解决方案目录为:PS D:\_code\testnetcore\EFCoreTestApi>PS D:\_code\testnetcore\EFCoreTestApi> cd DbFirstTestPS D:\_code\testnetcore\EFCoreTestApi\DbFirstTest>在控制台程序的根目录下,执行命令:
dotnet ef dbcontext scaffold "server=localhost;database=efcore;uid=sa;pwd=Qwe123456;" Microsoft.EntityFrameworkCore.SqlServer --data-annotations --context EfCoreContext --context-dir Data --output-dir Models--data-annotations:数据注释在实体上
--context EfCoreContext:上下文指定命名为 EfCoreContext
--context-dir Data:上下文保存在根目录的 Data 文件夹下
--output-dir Models:实体保存在根目录的 Models 文件夹下
在 Program.cs 添加测试代码:
EfCoreContext db = new EfCoreContext();Test test = new Test(){ Id = Guid.NewGuid(), Name = "Add"};db.Tests.Add(test);db.SaveChanges();在项目根目录下,执行:
dotnet build #编译dotnet run #运行执行以后,可以看到,数据库中添加了相应的记录。
Gitee:https://gitee.com/lisheng741/testnetcore/tree/master/EFCoreTestApi/DbFirstTest
Github:https://github.com/lisheng741/testnetcore/tree/master/EFCoreTestApi/DbFirstTest
EF Core官方文档:反向工程