Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MigrationHistory as entity in DbContext in Entity Framework 7

I'm trying to get the (by Entity Framework generated) table __EFMigrationsHistoryas an entity into my database context:

enter image description here

In Entity Framework 6 this worked fantastically, but did anyone tried it in EntityFramework 7?

What I tried is, to just add a new class __EFMigrationsHistory - but it'd be too easy - there is already a table named __EFMigrationsHistory in the database (thanks...)

Then I read about that HistoryRow, I shall inherit a class from. So I created the class

public class MigrationsHistory : HistoryRow 
{ 
    //... constructor etc.
}

started a migration and: I got two migration-history-tables (but only the original one works)

So I read on and searched for interfaces and classes to implement/inherit from. I found SqlServerHistoryRepository - looks nice. I created an new database context inheriting from SqlServerHistoryRepository (like I'd have done it in EF6). - But this is not a context-class, so I can not add it in Startup.cs (like I did with my default applicationcontext)

So I checked the DbContext for maybe add the history-table somewhere (like in EF6), but there is nothing for adding the table to my context.

So: Anyone already tried to add the migration-history to his context? Anyone was successful?

like image 299
Matthias Burger Avatar asked Oct 21 '25 05:10

Matthias Burger


2 Answers

Whilst I experimented with bricelam's answer with no success with EF Core 2.0, in Microsoft.EntityFrameworkCore there's a method;

// .NET Core 1.0 + Platform Extensions
// Microsoft.EntityFrameworkCore.Relational, Version=1.1.0.0, PublicKeyToken=adb9793829ddae60

namespace Microsoft.EntityFrameworkCore
{
    public static class RelationalDatabaseFacadeExtensions
    {
        public static IEnumerable<string> GetAppliedMigrations(this DatabaseFacade databaseFacade);
    }
}

Call it as follows;

var dbcontext = new DbContext();
IEnumerable<string> history = dbcontext.Database.GetAppliedMigrations();
like image 57
wonea Avatar answered Oct 23 '25 20:10

wonea


Mapping to the table by name should work (it is that easy), you just need to ensure you don't try to re-create it (e.g. by accidentally calling DbContext.Database.EnsureCreate())

class MyContext : DbContext
{
    public DbSet<AppliedMigration> AppliedMigrations { get; set; }
}

[Table("__EFMigrationsHistory")]
class AppliedMigration
{
    [Column("MigrationId")]
    public string Id { get; set; }

    [Column("ProductVersion")]
    public string EFVersion { get; set; }
}
like image 27
bricelam Avatar answered Oct 23 '25 18:10

bricelam