Search code examples
c#asp.net-core.net-coreasp.net-core-2.1entity-framework-core-2.1

EF Core 2.1. Add custom column to MigrationHistory table


I use EF Core 2.1 Code-First.

SELECT * FROM [dbo].[__MigrationsHistory] returns table from 2 columns

  • MigrationId
  • ProductVersion

I am looking for a way to add one more column AppliedOn which will store the time when migration was really applied to database.


Solution

  • You could do that in SQL :

    alter table [dbo].[__MigrationHistory] add AppliedOn Datetime default getdate()
    

    When EF applies a migration to the database it inserts a row in the table __MigrationHistory. This SQL Script adds the column AppliedOn with a default value at getDate(). When a row is inserted the column will contain the current datetime of this insert.

    Or, you could do the same thing with an EF Migration :

    By adding to the first migration(or to a new migration):

    public partial class Intial : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<DateTime>(
                name: "AppliedOnUtc",
                schema: "Conversations",
                table: "__MigrationsHistory",                
                defaultValueSql: "GETUTCDATE()"
            );
        }
         ....
    }