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-12-29 01:51:30

问题


I'm developing web app and near it small command line application that install ef core tables in the DB. Last can be done calling dbContext.Database.Migrate(); and this works.

Now I want to provide unistall option (with this app).

But how to remove migrations (means call functionality of dotnet ef database update 0 from my code) ?

It could be not one command call (as it was in case with dbContext.Database.Migrate();). But snippet with loop through all migrations in migrations assembly and call of 'Downs'.


回答1:


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);



回答2:


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



来源:https://stackoverflow.com/questions/52064291/how-to-uninstall-ef-core-tables-or-how-to-remove-all-migrations-or-how-to-cal

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