Reputation: 494
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?
Upvotes: 14
Views: 9759
Reputation: 5814
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.
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}");
Upvotes: 13
Reputation: 7113
Getting last migrationId in Ef Core
_context.Database.GetMigrations().Last()
Upvotes: 4
Reputation: 14640
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();
}
Upvotes: 18