Entity Framework 7 – Code First – 使用 CLI
关于使用命令行 (CLI) 的 EF7 – Code First 方法的教程
1. 引言
Entity Framework Core 更倾向于“Code First”方法,该方法允许使用命令行“CLI EF Core 工具”从 Entity Framework 模型创建数据库。本文旨在概述创建数据库的实际步骤,并列出在代码更改后“迁移/更新”数据库所需的命令行命令。
1.2. EFCorePowerTools
如果本文没有提及 EFCorePowerTools
[3],那将是不完整的。EFCorePowerTools
是一个 GUI“社区开源”工具,旨在支持与 EF 相关的操作。在撰写本文时(2023年5月),它们只提供一些“预览”功能,并且实际上不适用于我们这里的“Code First”方法。在这里,我们重点关注“官方”命令行界面 (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
。 相应的预期结果将是一个名为 Test1
的数据库,其中只有一个数据库表 Persons
。
这就是“Code First”方法,我们首先创建了 Entity
类,然后我们将从代码中创建数据库表。 为此,我们需要工具,在这种情况下,是 CLI EF Core 工具。
2.2. SqlServer 数据库
我们已经准备好 SqlServer,并在 appsettings.json 文件中配置了数据库连接字符串,该字符串将用于创建数据库。
3. 安装 CLI EF Core 工具
您需要安装 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
以下是执行结果
以下是结果。 请注意,已创建了 Migration 文件夹,其中包含迁移文件。
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
以下是执行结果
以下是结果。 请注意,在 Migration 文件夹中,文件 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) 使用 CLI EF Core 工具从 EF 模型生成“Code First”数据库。 过程并不难,尽管不太直观。
在撰写本文时(2023年5月),GUI “社区开源”工具 EFCorePowerTools
在“Code First”方法中不支持迁移。
9. 参考文献
- [1] https://learn.microsoft.com/en-us/ef/core/cli/
- [2] https://learn.microsoft.com/en-us/ef/core/managing-schemas/scaffolding/?tabs=dotnet-core-cli
- [3] https://github.com/ErikEJ/EFCorePowerTools/
- [4] https://www.entityframeworktutorial.net/efcore/working-with-stored-procedure-in-ef-core.aspx
- [5] https://github.com/dotnet/efcore/issues/15105
10. 历史
- 2023年6月2日:初始版本