Entity Framework Core的使用

Entity Framework Core的使用

如果您想要根据模型创建数据库表,可以使用Entity Framework Core的迁移功能。迁移允许您在模型更改时更新数据库架构,而无需手动创建或修改表。

要使用迁移,您需要执行以下步骤:

  • 1、安装 Microsoft.EntityFrameworkCore.Tools 包,以便在命令行中使用 dotnet ef 命令。
  • 2、在项目目录中运行 dotnet ef migrations add InitialCreate
    命令,以创建初始迁移。这将生成一个包含数据库架构创建代码的迁移类。
  • 3、运行 dotnet ef database update
    命令,以将迁移应用于数据库。这将创建数据库表并更新架构。

如果您以后对模型进行了更改,可以再次运行 dotnet ef migrations add 命令来创建新的迁移,并使用 dotnet ef database update 命令将其应用于数据库。

(1) Getting Started - EF Core | Microsoft Learn. https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app.
(2) Creating and Configuring a Model - EF Core | Microsoft Learn. https://learn.microsoft.com/en-us/ef/core/modeling/.
(3) Create database from model using Entity Framework Core and ASP.NET Core … http://www.binaryintellect.net/articles/87446533-54b3-41ad-bea9-994091686a55.aspx.

dotnet ef的使用

dotnet ef 是 Entity Framework Core 的命令行接口工具,它可以执行设计时开发任务,例如创建迁移、应用迁移和根据现有数据库生成模型的代码。这些命令是跨平台 dotnet 命令的扩展,它是 .NET Core SDK 的一部分。这些工具适用于 .NET Core 项目。

要安装 dotnet ef 工具,您可以使用以下命令将其安装为全局工具:

dotnet tool install --global dotnet-ef

安装完成后,您可以在命令行中使用 dotnet ef 命令。例如,要创建初始迁移,您可以在项目目录中运行以下命令:

dotnet ef migrations add InitialCreate

这将生成一个包含数据库架构创建代码的迁移类。然后,您可以运行以下命令将迁移应用于数据库:

dotnet ef database update

这将创建数据库表并更新架构。

(1) Command Line Interface commands - Learn Entity Framework Core. https://www.learnentityframeworkcore.com/migrations/commands/cli-commands.
(2) EF Core tools reference (.NET CLI) - EF Core | Microsoft Learn. https://learn.microsoft.com/en-us/ef/core/cli/dotnet.
(3) EF Core 工具参考 (.NET CLI) - EF Core | Microsoft Learn. https://learn.microsoft.com/zh-cn/ef/core/cli/dotnet.
(4) EF Core 工具參考 (.NET CLI) - EF Core | Microsoft Learn. https://learn.microsoft.com/zh-tw/ef/core/cli/dotnet.

dotnet ef migrations add

是的,您可以将 InitialCreate 更改为其他名称。dotnet ef migrations add 命令的参数是迁移的名称,它用于标识迁移。您可以使用任何名称来标识迁移,只要它是唯一的并且符合C#标识符的命名规则。

例如,如果您想要创建一个名为 AddProductTable 的迁移,您可以运行以下命令:

dotnet ef migrations add AddProductTable

这将创建一个名为 AddProductTable 的迁移类,您可以在其中定义数据库架构更改。

猜你喜欢

转载自blog.csdn.net/wkj001/article/details/145908719
今日推荐