Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Migrations: get database version as string

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?

like image 416
user1898153 Avatar asked Aug 01 '14 13:08

user1898153


3 Answers

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();
}
like image 111
Yuliam Chandra Avatar answered Sep 20 '22 23:09

Yuliam Chandra


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}");
like image 28
Christoph Lütjen Avatar answered Sep 20 '22 23:09

Christoph Lütjen


Getting last migrationId in Ef Core

_context.Database.GetMigrations().Last()
like image 4
MichaelS Avatar answered Sep 22 '22 23:09

MichaelS