如何卸载EF Core表?或者如何删除所有迁移?或者如何从用户代码调用`dotnet ef database update 0`? [英] How to uninstall EF Core tables? Or how to remove all migrations ? Or how to call `dotnet ef database update 0` from user code?
问题描述
我正在开发网络应用程序,并且正在开发小型命令行应用程序,该应用程序将ef核心表安装在数据库中。最后可以通过调用 dbContext.Database.Migrate();
来完成。
现在我想提供 unistall
选项(带有此应用程序)。
但是如何删除迁移(意味着调用<$ c $的功能c> dotnet ef数据库从我的代码更新0 )?
可能不是一个命令调用(如 dbContext.Database.Migrate()那样;
)。但是,在迁移程序集和调用 Downs的所有迁移中都有循环的代码段。
EF核心仅公开提供 dbContext.Database.Migrate();
扩展方法,用于迁移最新版本。在应用中提到EF Core文档的运行时迁移部分,其中还包含以下内容
注意
此方法建立在
IMigrator
服务的基础上,该服务可用于更高级的方案。使用DbContext.GetService< IMigrator>()
进行访问。
其中为您提供了解决方案,因为 IMigrator
界面提供了 Migrate
方法,该方法接受具有相同参数的可选 targetMigration
参数语义,例如 dotnet ef数据库更新
或 Update-Database
PM命令。传递 0
(这是 Migration.InitialDatabase
常量的值)将执行有问题的操作。 / p>
您还需要使用来添加以下
:
使用Microsoft.EntityFrameworkCore.Infrastructure;
使用Microsoft.EntityFrameworkCore.Migrations;
和类似这样的代码:
var migrator = dbContext.GetService< IMigrator>();
migrator.Migrate(Migration.InitialDatabase);
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'.
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. UseDbContext.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 using
s:
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
and code like this:
var migrator = dbContext.GetService<IMigrator>();
migrator.Migrate(Migration.InitialDatabase);
这篇关于如何卸载EF Core表?或者如何删除所有迁移?或者如何从用户代码调用`dotnet ef database update 0`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!