Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting current MigrationId

I want to get the "version" of the database i.e. the MigrationId of the last row in the __EFMigrationHistory table.

Since it's not possible to run raw SQL in Entity Framework Core without a DbSet, how can I get this information?

like image 654
ghosttie Avatar asked Mar 01 '26 11:03

ghosttie


2 Answers

In EF Core 1.1, you can use the following.

var currentMigration = dbContext.Database.GetAppliedMigrations().LastOrDefault();
like image 51
bricelam Avatar answered Mar 03 '26 01:03

bricelam


One option you have is to add the __EFMigrationsHistory table to your context. Create a model, something like this:

[Table("__EFMigrationsHistory")]
public class MigrationHistory
{
    [Key]
    [MaxLength(150)]
    public string MigrationId { get; set; }

    [MaxLength(32)]
    public string ProductVersion { get; set; }

}

Add a DbSet to your model:

public DbSet<MigrationHistory> MigrationHistories { get; set; }

And now you can query the table as you would any other:

var lastMigration = context.MigrationHistories
    .OrderBy(mh => mh.MigrationId)
    .Last();
like image 32
DavidG Avatar answered Mar 02 '26 23:03

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!