I'm working on a web app using EF5. I'd like to display the database version (i.e. the name of the migration) on the admin pages... that way, if the site is deployed to an environment where I don't have database admin rights, I can still log into the back end to find the version if I need to generate an upgrade script. Is there a property e.g. of the DBContext I can use to get this information?
Entity framework will create migration history table to manage the database version.
Migrations history table is a table used by Code First Migrations to store details about migrations applied to the database. By default the name of the table in the database is __MigrationHistory and it is created when applying the first migration do the database. Source
You can use MigrationId
column to be the database version. The value of the column looks like 201408011306353_InitialCreate
. Just get the last row order by the first 15 character descending.
using (var context = new AppContext())
{
var query = "select top 1 MigrationId from __MigrationHistory order by LEFT(MigrationId, 15) desc";
var migrationId = context.Database.SqlQuery<string>(query).FirstOrDefault();
}
Entity framework core provides:
context.Database.GetMigrations()
Gets all the migrations that are defined in the configured migrations assembly.
context.Database.GetAppliedMigrations()
Gets all migrations that have been applied to the target database.
See https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade?view=efcore-2.0
Example
// _context = instance of MyDbContext from ctor
var lastAppliedMigration = _context.Database.GetAppliedMigrations().LastOrDefault();
var lastDefinedMigration = _context.Database.GetMigrations().LastOrDefault();
Console.WriteLine($"Last applied migration id: {lastAppliedMigration}");
Console.WriteLine(lastAppliedMigration == lastDefinedMigration
? "Database is up to date."
: $"There are outstanding migrations. Last defined migration is: {lastDefinedMigration}");
Getting last migrationId in Ef Core
_context.Database.GetMigrations().Last()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With