How to uninstall EF Core tables? Or how to remove all migrations ? Or how to call `dotnet ef database update 0` from user code?

南笙酒味 提交于 2019-11-28 14:30:26

EF Core provides publicly only the dbContext.Database.Migrate(); extension method used to migrate the latest version. It's mentioned in the Applying migrations at runtime section of the EF Core documentation, which also contains the following

Note

This method builds on top of the IMigrator service, which can be used for more advanced scenarios. Use DbContext.GetService<IMigrator>() to access it.

which gives you the solution, because IMigrator interface provides Migrate method accepting optional targetMigration parameter with the same semantics as the dotnet ef database update or Update-Database PM commands. Passing "0" (which is the value of the Migration.InitialDatabase constant) will perform the operation in question.

You'll need the following additional usings:

using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;

and code like this:

var migrator = dbContext.GetService<IMigrator>();
migrator.Migrate(Migration.InitialDatabase);

you can do this by dropping down to some lower-level components.

dbContext.GetService<IMigrator>().Migrate(targetMigration);

Use the constant Migration.InitialDatabase to revert all migrations.

Migration.InitialDatabase

  • Namespace: Microsoft.EntityFrameworkCore.Migrations
  • Assembly: Microsoft.EntityFrameworkCore.Relational.dll
  • Description: The migration identifier for the empty database.
  • Declaration: public const string InitialDatabase;

Reference: https://github.com/aspnet/EntityFrameworkCore/issues/9968#issuecomment-335295576

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!