问题
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. 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);
回答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