目录
1. 引言
Entity Framework Core优先采用“Code First”方法,该方法允许使用命令行“CLI EF Core工具”从Entity Framework Model创建数据库。本文旨在概述创建数据库的实用步骤,并枚举必要的命令行命令,以便在代码更改后“迁移/更新”数据库。
1.2. EFCorePower工具
如果不提及EFCorePowerTools [3],本文就不完整,这是一个GUI“社区开源”工具,旨在支持与EF相关的操作。在撰写本文时(2023年5月),它们仅提供一些“预览”功能,实际上不适用于此处的“代码优先”方法。在这里,我们重点介绍“官方”命令行界面(CLI)方法。
2. 示例项目
2.1. 示例控制台.NET7应用程序
我们创建了一个示例控制台。我们将使用的NET7应用程序。下面是应用程序的屏幕截图,后跟代码。
//=====Person.cs========================================
public class Person
{
public int Id { get; set; }
public string? Name { get; set; }
public int Age { get; set; }
public string? Address { get; set; }
}
//=====Test1DbContext.cs====================================
public class Test1DbContext : DbContext
{
public Test1DbContext(DbContextOptions<Test1DbContext> options)
: base(options)
{
}
public DbSet<Person> Persons { get; set; }
}
//=====Test1DbContextFactory.cs=============================
public class Test1DbContextFactory : IDesignTimeDbContextFactory<Test1DbContext>
{
static Test1DbContextFactory()
{
IConfiguration config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.Build();
connectionString = config["ConnectionStrings:Test1Connection"];
Console.WriteLine("ConnectionString:" + connectionString);
}
static string? connectionString = null;
public Test1DbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<Test1DbContext>();
optionsBuilder.UseSqlServer(connectionString);
return new Test1DbContext(optionsBuilder.Options);
}
}
//=====appsettings.json============================
{
"ConnectionStrings": {
"Test1Connection": "Data Source=.;User Id=sa;Password=dbadmin1!;
Initial Catalog=Test1;Encrypt=False"
}
}
//============================
如您所见,我们只创建了一个类EntityDataModel,即Person。我们的上下文Test1DbContext只包含一个DbSet<>属性Persons。相应的计划结果将是一个仅包含一个数据库表Persons的数据库Test1。
这就是我们首先创建Entity类的“代码优先”方法,然后我们将从代码创建数据库表。为此,我们需要工具,在本例中为 CLI EF Core工具。
2.2. SqlServer数据库
我们已准备好SqlServer,并在 appsettings.json 文件中配置了数据库连接字符串,该文件将用于创建数据库。
3. 安装CLI EF Core Tools
需要安装CLI EF Core工具并导航到项目文件夹。以下是您将需要的命令:
dotnet tool uninstall --global dotnet-ef
dotnet tool install --global dotnet-ef --version 7.0.5
cd C:\Tmp\Example3\Example3\
以下是屏幕截图:
4. 创建数据库
4.1. 第1步——创建迁移
现在是做实际工作的时候了。您需要做的第一件事是创建迁移文件。您将需要以下命令:
// This will create .cs migration files in the directory Migration
// Note that "Initial" is an arbitrary name
dotnet ef migrations add Initial -o Migrations -c Example3.Test1DbContext
这是执行:
这是结果。请注意,已创建“迁移”文件夹,其中包含迁移文件。
4.2. 第2步——创建数据库
若要实际创建数据库,需要以下命令:
// This will apply all migrations to database that are not
// already applied. It will create the database if needed.
dotnet ef database update -c Example3.Test1DbContext
这是执行:
这是结果。
已创建SqlServer数据库Test1,并在其中包含表Persons。
另请注意,数据库表__EFMigrationsHistory已创建,它跟踪已应用的迁移。
5. 更改代码/实体数据模型
一种典型的情况是,你希望随着时间的推移更改实体数据模型。在这里,我们将通过向Person类添加一个新属性来说明它。我们将该Profession属性添加到类中。
public class Person
{
public int Id { get; set; }
public string? Name { get; set; }
public int Age { get; set; }
public string? Address { get; set; }
public string? Profession { get; set; }
}
现在我们遇到的情况是代码(实体数据模型)与数据库不同步。我们需要解决这个问题。
6. 升级数据库
6.1. 第1步——创建迁移
您需要做的第一件事是创建迁移文件。您将需要以下命令:
// This will create .cs migration files in the directory Migration
// Note that "Work" is an arbitrary name
dotnet ef migrations add Work -o Migrations -c Example3.Test1DbContext
这是执行:
这是结果。请注意,在“迁移”文件夹中,已创建20230530053706_Work.cs文件。
6.2. 第2步——更新数据库
若要实际更新数据库,需要以下命令:
// This will apply all migrations to database that are not
// already applied. It will create the database if needed.
dotnet ef database update -c Example3.Test1DbContext
这是执行:
结果如下:
已创建SqlServer数据库Test1,其中的表是Persons,Profession列已经创建。
另请注意,数据库表__EFMigrationsHistory跟踪已应用的迁移。
7. 测试申请
我们将创建一些代码来测试EF生成的模型。以下是测试代码:
using Example3.EntityDataModel;
using Example3;
Console.WriteLine("Hello from Example3");
using Test1DbContext ctx = new Test1DbContextFactory().CreateDbContext(new string[0]);
Person per1 = new Person { Name = "Mark", Age = 33,
Address = "Belgrade, Serbia", Profession = "Programmer" };
ctx.Persons.Add(per1);
ctx.SaveChanges();
Console.WriteLine("Table Persons ==================================");
foreach (var person in ctx.Persons)
{
Console.WriteLine("Id:" + person.Id.ToString() + " Name:" + person.Name);
}
这是执行结果:
这是数据库表Persons:
8. 结论
我们演示了如何使用CLI EF Core工具从命令行(CLI)从EF模型生成“Code First”数据库。这个过程并不困难,虽然不是那么直观。
在撰写本文时(2023 年 5 月),GUI“社区开源”工具EFCorePowerTools不支持“代码优先”方法的迁移。
9. 参考资料
- [1] Entity Framework Core tools reference - EF Core | Microsoft Learn
- [2] Reverse Engineering - EF Core | Microsoft Learn
- [3] GitHub - ErikEJ/EFCorePowerTools: Entity Framework Core Power Tools - reverse engineering, migrations and model visualization in Visual Studio & CLI
- [4] Working with Stored Procedure in Entity Framework Core
- [5] Reverse engineer/scaffold stored procedures · Issue #15105 · dotnet/efcore · GitHub
https://www.codeproject.com/Articles/5361950/Entity-Framework-7-Code-First-Using-CLI