EF Core 的基本使用

发布时间 2023-09-03 16:33:09作者: 虎虎生威啊

基本命令

EF Core的迁移(Migration)是一种用于管理数据库架构变化的功能,它可以根据你的数据模型自动生成和执行数据库创建或者更新的SQL语句。EF Core提供了一些命令行工具,让你可以方便地操作迁移。以下是一些常用的迁移命令:

  • dotnet ef migrations add <name>: 这个命令用于创建一个新的迁移,它会根据你的数据模型和当前的数据库架构,生成一个包含SQL语句的C#类,用于更新数据库。你需要给这个迁移一个有意义的名字,例如InitialCreate或者AddStudentAge。这个命令会在你的项目中创建一个名为Migrations的文件夹,用于存放所有的迁移类。
  • dotnet ef migrations remove: 这个命令用于删除最近添加的迁移,它会从你的项目中删除对应的迁移类。如果你想删除一个旧的或者中间的迁移,你需要先回滚到那个迁移之前,然后再删除它,再重新添加后面的迁移。
  • dotnet ef migrations list: 这个命令用于列出所有已经添加的迁移,它会按照时间顺序显示迁移的名字和ID。
  • dotnet ef database update: 这个命令用于更新数据库,它会执行最新的迁移类中的SQL语句,把数据库架构变更为和数据模型一致。如果你没有指定任何参数,它会更新到最新的迁移。如果你指定了一个迁移的名字或者ID,它会更新到那个迁移。如果你指定了0作为参数,它会回滚到空数据库。
  • dotnet ef database drop: 这个命令用于删除数据库,它会把整个数据库文件或者表删除。这个命令需要谨慎使用,因为它会丢失所有的数据。

删除迁移失败的原因

我很抱歉你遇到了错误。根据你的输出,我发现你的错误是因为你使用了错误的命令来删除迁移。你不能在dotnet ef migrations remove这个命令后面加上迁移的名字或者ID,这个命令只能删除最近添加的迁移。如果你想删除一个旧的或者中间的迁移,你需要先回滚到那个迁移之前,然后再删除它,再重新添加后面的迁移。

如果你想删除20230903032747_set villa table UpdatedDate is nullable这个迁移,你可以执行以下命令:

dotnet ef database update 20230902135255_create villa table
dotnet ef migrations remove

删除过程记录

列出所有的迁移

song@songdembp@ MagicVilla_VillaAPI % dotnet ef migrations list
Build started...
Build succeeded.
The Entity Framework tools version '7.0.9' is older than that of the runtime '7.0.10'. Update the tools for the latest features and bug fixes. See https://aka.ms/AAc1fbw for more information.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT "MigrationId", "ProductVersion"
      FROM "__EFMigrationsHistory"
      ORDER BY "MigrationId";
20230902135255_create villa table
20230903032747_set villa table UpdatedDate is nullable

删除迁移

删除失败

song@songdembp@ MagicVilla_VillaAPI % dotnet ef database update 20230903032747
Build started...
Build succeeded.
The Entity Framework tools version '7.0.9' is older than that of the runtime '7.0.10'. Update the tools for the latest features and bug fixes. See https://aka.ms/AAc1fbw for more information.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT "MigrationId", "ProductVersion"
      FROM "__EFMigrationsHistory"
      ORDER BY "MigrationId";
System.InvalidOperationException: The migration '20230903032747' was not found.
   at Microsoft.EntityFrameworkCore.Migrations.MigrationsAssemblyExtensions.GetMigrationId(IMigrationsAssembly assembly, String nameOrId)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.PopulateMigrations(IEnumerable`1 appliedMigrationEntries, String targetMigration, IReadOnlyList`1& migrationsToApply, IReadOnlyList`1& migrationsToRevert, Migration& actualTargetMigration)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.GetMigrationCommandLists(IReadOnlyList`1 appliedMigrationEntries, String targetMigration)+MoveNext()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String targetMigration, String connectionString, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
The migration '20230903032747' was not found.

删除成功(要给全称)

song@songdembp@ MagicVilla_VillaAPI % dotnet ef database update "20230902135255_create villa table"

Build started...
Build succeeded.
The Entity Framework tools version '7.0.9' is older than that of the runtime '7.0.10'. Update the tools for the latest features and bug fixes. See https://aka.ms/AAc1fbw for more information.
..............................

查看删除之后的迁移

  1. 有个Pending中
song@songdembp@ MagicVilla_VillaAPI % dotnet ef migrations list
Build started...
Build succeeded.
The Entity Framework tools version '7.0.9' is older than that of the runtime '7.0.10'. Update the tools for the latest features and bug fixes. See https://aka.ms/AAc1fbw for more information.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT "MigrationId", "ProductVersion"
      FROM "__EFMigrationsHistory"
      ORDER BY "MigrationId";
20230902135255_create villa table
20230903032747_set villa table UpdatedDate is nullable (Pending)

删除哪个Pending迁移

  1. 当然也可以手动去文件夹中删除
song@songdembp@ MagicVilla_VillaAPI % dotnet migrations remove 
Could not execute because the specified command or file was not found.
Possible reasons for this include:
  * You misspelled a built-in dotnet command.
  * You intended to execute a .NET program, but dotnet-migrations does not exist.
  * You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.
song@songdembp@ MagicVilla_VillaAPI % dotnet ef migrations remove
Build started...
Build succeeded.
The Entity Framework tools version '7.0.9' is older than that of the runtime '7.0.10'. Update the tools for the latest features and bug fixes. See https://aka.ms/AAc1fbw for more information.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT "MigrationId", "ProductVersion"
      FROM "__EFMigrationsHistory"
      ORDER BY "MigrationId";
Removing migration '20230903032747_set villa table UpdatedDate is nullable'.
Reverting the model snapshot.
Done.

剩下的迁移

song@songdembp@ MagicVilla_VillaAPI % dotnet ef migrations list
Build started...
Build succeeded.
The Entity Framework tools version '7.0.9' is older than that of the runtime '7.0.10'. Update the tools for the latest features and bug fixes. See https://aka.ms/AAc1fbw for more information.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (5ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT "MigrationId", "ProductVersion"
      FROM "__EFMigrationsHistory"
      ORDER BY "MigrationId";
20230902135255_create villa table