How to Customize Migration History Table with Entity Framework CoreReset Entity-Framework MigrationsEF 6 - Adding Custom Fields/Data to the __MigrationHistory tableEntity Framework Core with combined keys and active recordEntity Framework Core: Script-Migration not recognizing migrations when creating scriptEntity Framework Core Mutiple DbContext Migrations in same databaseDatabase migration fail while using entity framework coreEntity Framework Core 2.0, migrations for both SQL Server and Postgres?Entity Framework Core fluent api One-To-Many and One-To-One produces duplicate foreign keyGet table value without a model in Entity Framework CoreEntity Framework custom type

Is it OK to throw pebbles and stones in streams, waterfalls, ponds, etc.?

tikz: draw multicolor curve with smooth gradient

Does a lens with a bigger max. aperture focus faster than a lens with a smaller max. aperture?

Avoiding repetition when using the "snprintf idiom" to write text

Can I hire several veteran soldiers to accompany me?

Does an NPC know when a character has passed the save for Truth Serum?

Can I deep fry food in butter instead of vegetable oil?

Why did the Apple IIe make a hideous noise if you inserted the disk upside down?

Is it OK to say "The situation is pregnant with a crisis"?

"nunca" placement after a verb with "no"

Why didn't Caesar move against Sextus Pompey immediately after Munda?

How far can gerrymandering go?

How soon after takeoff can you recline your airplane seat?

Why will we fail creating a self sustaining off world colony?

Reaction mechanism of rearrangement

Enterprise Layers and Naming Conventions

Why doesn't SpaceX land boosters in Africa?

What is the meaning of "it" in "as luck would have it"?

What is my external HDD doing?

Is it advisable to inform the CEO about his brother accessing his office?

Any Tips On Writing Extended Recollection In A Novel

My mom helped me cosign a car and now she wants to take it

Does friction always oppose motion?

Basis and cardinality



How to Customize Migration History Table with Entity Framework Core


Reset Entity-Framework MigrationsEF 6 - Adding Custom Fields/Data to the __MigrationHistory tableEntity Framework Core with combined keys and active recordEntity Framework Core: Script-Migration not recognizing migrations when creating scriptEntity Framework Core Mutiple DbContext Migrations in same databaseDatabase migration fail while using entity framework coreEntity Framework Core 2.0, migrations for both SQL Server and Postgres?Entity Framework Core fluent api One-To-Many and One-To-One produces duplicate foreign keyGet table value without a model in Entity Framework CoreEntity Framework custom type













0















I'm setting up Entity Framework Core in a new API to deploy to an existing SQL Server database that is used by Entity Framework 4.6 applications. There is one Migration History table that is shared by other applications, and has 2 fields in it that need to be populated for each entry: ContextKey, and Model. Entity Framework Core does not have a Context Key, and does not save the Model to the Migration History table.



I've already created a HistoryRepository : SqlServerHistoryRepository and configured Entity Framework Core to use it, but the ConfigureTable method only allows you to create additional columns, but not actually populate each record as it gets inserted with custom data. Providing a default value to the column is not a solution.



public class HistoryRepository : SqlServerHistoryRepository

public HistoryRepository(HistoryRepositoryDependencies dependencies)
: base(dependencies)


protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)

base.ConfigureTable(history);
history.Property<string>("ContextKey")
.HasMaxLength(300);
history.Property<byte[]>("Model");



services.AddDbContext<MDSContext>(options =>
options.UseLazyLoadingProxies()
.UseSqlServer(
connectionString,
x => x.MigrationsHistoryTable("__MigrationHistory")).ReplaceService<Microsoft.EntityFrameworkCore.Migrations.IHistoryRepository, Burkhart.CoreServices.IncomingOrders.Core.Models.Base.HistoryRepository>()
);


I should be able to provide a custom value for ContextKey and Model dynamically










share|improve this question


























    0















    I'm setting up Entity Framework Core in a new API to deploy to an existing SQL Server database that is used by Entity Framework 4.6 applications. There is one Migration History table that is shared by other applications, and has 2 fields in it that need to be populated for each entry: ContextKey, and Model. Entity Framework Core does not have a Context Key, and does not save the Model to the Migration History table.



    I've already created a HistoryRepository : SqlServerHistoryRepository and configured Entity Framework Core to use it, but the ConfigureTable method only allows you to create additional columns, but not actually populate each record as it gets inserted with custom data. Providing a default value to the column is not a solution.



    public class HistoryRepository : SqlServerHistoryRepository

    public HistoryRepository(HistoryRepositoryDependencies dependencies)
    : base(dependencies)


    protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)

    base.ConfigureTable(history);
    history.Property<string>("ContextKey")
    .HasMaxLength(300);
    history.Property<byte[]>("Model");



    services.AddDbContext<MDSContext>(options =>
    options.UseLazyLoadingProxies()
    .UseSqlServer(
    connectionString,
    x => x.MigrationsHistoryTable("__MigrationHistory")).ReplaceService<Microsoft.EntityFrameworkCore.Migrations.IHistoryRepository, Burkhart.CoreServices.IncomingOrders.Core.Models.Base.HistoryRepository>()
    );


    I should be able to provide a custom value for ContextKey and Model dynamically










    share|improve this question
























      0












      0








      0








      I'm setting up Entity Framework Core in a new API to deploy to an existing SQL Server database that is used by Entity Framework 4.6 applications. There is one Migration History table that is shared by other applications, and has 2 fields in it that need to be populated for each entry: ContextKey, and Model. Entity Framework Core does not have a Context Key, and does not save the Model to the Migration History table.



      I've already created a HistoryRepository : SqlServerHistoryRepository and configured Entity Framework Core to use it, but the ConfigureTable method only allows you to create additional columns, but not actually populate each record as it gets inserted with custom data. Providing a default value to the column is not a solution.



      public class HistoryRepository : SqlServerHistoryRepository

      public HistoryRepository(HistoryRepositoryDependencies dependencies)
      : base(dependencies)


      protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)

      base.ConfigureTable(history);
      history.Property<string>("ContextKey")
      .HasMaxLength(300);
      history.Property<byte[]>("Model");



      services.AddDbContext<MDSContext>(options =>
      options.UseLazyLoadingProxies()
      .UseSqlServer(
      connectionString,
      x => x.MigrationsHistoryTable("__MigrationHistory")).ReplaceService<Microsoft.EntityFrameworkCore.Migrations.IHistoryRepository, Burkhart.CoreServices.IncomingOrders.Core.Models.Base.HistoryRepository>()
      );


      I should be able to provide a custom value for ContextKey and Model dynamically










      share|improve this question














      I'm setting up Entity Framework Core in a new API to deploy to an existing SQL Server database that is used by Entity Framework 4.6 applications. There is one Migration History table that is shared by other applications, and has 2 fields in it that need to be populated for each entry: ContextKey, and Model. Entity Framework Core does not have a Context Key, and does not save the Model to the Migration History table.



      I've already created a HistoryRepository : SqlServerHistoryRepository and configured Entity Framework Core to use it, but the ConfigureTable method only allows you to create additional columns, but not actually populate each record as it gets inserted with custom data. Providing a default value to the column is not a solution.



      public class HistoryRepository : SqlServerHistoryRepository

      public HistoryRepository(HistoryRepositoryDependencies dependencies)
      : base(dependencies)


      protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)

      base.ConfigureTable(history);
      history.Property<string>("ContextKey")
      .HasMaxLength(300);
      history.Property<byte[]>("Model");



      services.AddDbContext<MDSContext>(options =>
      options.UseLazyLoadingProxies()
      .UseSqlServer(
      connectionString,
      x => x.MigrationsHistoryTable("__MigrationHistory")).ReplaceService<Microsoft.EntityFrameworkCore.Migrations.IHistoryRepository, Burkhart.CoreServices.IncomingOrders.Core.Models.Base.HistoryRepository>()
      );


      I should be able to provide a custom value for ContextKey and Model dynamically







      entity-framework-core ef-migrations entity-framework-core-migrations






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 25 at 16:32









      GaryGary

      112 bronze badges




      112 bronze badges




















          1 Answer
          1






          active

          oldest

          votes


















          0














          I looked all over for solutions, but they all show you how to add a column and set a default value, but not how to set a value dynamically. I ended up digging into the ASP.NET Entity Framework Core source code at GitHub for the solution, so that I would share it with everyone else, as I know there are others that are looking for this information:



          Just override the GetInsertScript method on the HistoryRepository and insert your custom values. Here is the full solution:



          public class HistoryRepository : SqlServerHistoryRepository

          public HistoryRepository(HistoryRepositoryDependencies dependencies)
          : base(dependencies)


          protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)

          base.ConfigureTable(history);
          history.Property<string>("ContextKey")
          .HasMaxLength(300);
          history.Property<byte[]>("Model");

          public override string GetInsertScript(HistoryRow row)

          var stringTypeMapping = Dependencies.TypeMappingSource.GetMapping(typeof(string));
          return new StringBuilder().Append("INSERT INTO ")
          .Append(SqlGenerationHelper.DelimitIdentifier(TableName, TableSchema))
          .Append(" (")
          .Append(SqlGenerationHelper.DelimitIdentifier(MigrationIdColumnName))
          .Append(", ")
          .Append(SqlGenerationHelper.DelimitIdentifier(ProductVersionColumnName))
          .Append(", [ContextKey], [Model])")
          .Append("VALUES (")
          .Append(stringTypeMapping.GenerateSqlLiteral(row.MigrationId))
          .Append(", ")
          .Append(stringTypeMapping.GenerateSqlLiteral(row.ProductVersion))
          .Append($", 'ContextConstants.ContextName.ContextConstants.ContextSchemaName', 0x)")
          .AppendLine(SqlGenerationHelper.StatementTerminator)
          .ToString();




          Here is a link to the source code on github:
          https://github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore.Relational/Migrations/HistoryRepository.cs






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55342435%2fhow-to-customize-migration-history-table-with-entity-framework-core%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I looked all over for solutions, but they all show you how to add a column and set a default value, but not how to set a value dynamically. I ended up digging into the ASP.NET Entity Framework Core source code at GitHub for the solution, so that I would share it with everyone else, as I know there are others that are looking for this information:



            Just override the GetInsertScript method on the HistoryRepository and insert your custom values. Here is the full solution:



            public class HistoryRepository : SqlServerHistoryRepository

            public HistoryRepository(HistoryRepositoryDependencies dependencies)
            : base(dependencies)


            protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)

            base.ConfigureTable(history);
            history.Property<string>("ContextKey")
            .HasMaxLength(300);
            history.Property<byte[]>("Model");

            public override string GetInsertScript(HistoryRow row)

            var stringTypeMapping = Dependencies.TypeMappingSource.GetMapping(typeof(string));
            return new StringBuilder().Append("INSERT INTO ")
            .Append(SqlGenerationHelper.DelimitIdentifier(TableName, TableSchema))
            .Append(" (")
            .Append(SqlGenerationHelper.DelimitIdentifier(MigrationIdColumnName))
            .Append(", ")
            .Append(SqlGenerationHelper.DelimitIdentifier(ProductVersionColumnName))
            .Append(", [ContextKey], [Model])")
            .Append("VALUES (")
            .Append(stringTypeMapping.GenerateSqlLiteral(row.MigrationId))
            .Append(", ")
            .Append(stringTypeMapping.GenerateSqlLiteral(row.ProductVersion))
            .Append($", 'ContextConstants.ContextName.ContextConstants.ContextSchemaName', 0x)")
            .AppendLine(SqlGenerationHelper.StatementTerminator)
            .ToString();




            Here is a link to the source code on github:
            https://github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore.Relational/Migrations/HistoryRepository.cs






            share|improve this answer



























              0














              I looked all over for solutions, but they all show you how to add a column and set a default value, but not how to set a value dynamically. I ended up digging into the ASP.NET Entity Framework Core source code at GitHub for the solution, so that I would share it with everyone else, as I know there are others that are looking for this information:



              Just override the GetInsertScript method on the HistoryRepository and insert your custom values. Here is the full solution:



              public class HistoryRepository : SqlServerHistoryRepository

              public HistoryRepository(HistoryRepositoryDependencies dependencies)
              : base(dependencies)


              protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)

              base.ConfigureTable(history);
              history.Property<string>("ContextKey")
              .HasMaxLength(300);
              history.Property<byte[]>("Model");

              public override string GetInsertScript(HistoryRow row)

              var stringTypeMapping = Dependencies.TypeMappingSource.GetMapping(typeof(string));
              return new StringBuilder().Append("INSERT INTO ")
              .Append(SqlGenerationHelper.DelimitIdentifier(TableName, TableSchema))
              .Append(" (")
              .Append(SqlGenerationHelper.DelimitIdentifier(MigrationIdColumnName))
              .Append(", ")
              .Append(SqlGenerationHelper.DelimitIdentifier(ProductVersionColumnName))
              .Append(", [ContextKey], [Model])")
              .Append("VALUES (")
              .Append(stringTypeMapping.GenerateSqlLiteral(row.MigrationId))
              .Append(", ")
              .Append(stringTypeMapping.GenerateSqlLiteral(row.ProductVersion))
              .Append($", 'ContextConstants.ContextName.ContextConstants.ContextSchemaName', 0x)")
              .AppendLine(SqlGenerationHelper.StatementTerminator)
              .ToString();




              Here is a link to the source code on github:
              https://github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore.Relational/Migrations/HistoryRepository.cs






              share|improve this answer

























                0












                0








                0







                I looked all over for solutions, but they all show you how to add a column and set a default value, but not how to set a value dynamically. I ended up digging into the ASP.NET Entity Framework Core source code at GitHub for the solution, so that I would share it with everyone else, as I know there are others that are looking for this information:



                Just override the GetInsertScript method on the HistoryRepository and insert your custom values. Here is the full solution:



                public class HistoryRepository : SqlServerHistoryRepository

                public HistoryRepository(HistoryRepositoryDependencies dependencies)
                : base(dependencies)


                protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)

                base.ConfigureTable(history);
                history.Property<string>("ContextKey")
                .HasMaxLength(300);
                history.Property<byte[]>("Model");

                public override string GetInsertScript(HistoryRow row)

                var stringTypeMapping = Dependencies.TypeMappingSource.GetMapping(typeof(string));
                return new StringBuilder().Append("INSERT INTO ")
                .Append(SqlGenerationHelper.DelimitIdentifier(TableName, TableSchema))
                .Append(" (")
                .Append(SqlGenerationHelper.DelimitIdentifier(MigrationIdColumnName))
                .Append(", ")
                .Append(SqlGenerationHelper.DelimitIdentifier(ProductVersionColumnName))
                .Append(", [ContextKey], [Model])")
                .Append("VALUES (")
                .Append(stringTypeMapping.GenerateSqlLiteral(row.MigrationId))
                .Append(", ")
                .Append(stringTypeMapping.GenerateSqlLiteral(row.ProductVersion))
                .Append($", 'ContextConstants.ContextName.ContextConstants.ContextSchemaName', 0x)")
                .AppendLine(SqlGenerationHelper.StatementTerminator)
                .ToString();




                Here is a link to the source code on github:
                https://github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore.Relational/Migrations/HistoryRepository.cs






                share|improve this answer













                I looked all over for solutions, but they all show you how to add a column and set a default value, but not how to set a value dynamically. I ended up digging into the ASP.NET Entity Framework Core source code at GitHub for the solution, so that I would share it with everyone else, as I know there are others that are looking for this information:



                Just override the GetInsertScript method on the HistoryRepository and insert your custom values. Here is the full solution:



                public class HistoryRepository : SqlServerHistoryRepository

                public HistoryRepository(HistoryRepositoryDependencies dependencies)
                : base(dependencies)


                protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)

                base.ConfigureTable(history);
                history.Property<string>("ContextKey")
                .HasMaxLength(300);
                history.Property<byte[]>("Model");

                public override string GetInsertScript(HistoryRow row)

                var stringTypeMapping = Dependencies.TypeMappingSource.GetMapping(typeof(string));
                return new StringBuilder().Append("INSERT INTO ")
                .Append(SqlGenerationHelper.DelimitIdentifier(TableName, TableSchema))
                .Append(" (")
                .Append(SqlGenerationHelper.DelimitIdentifier(MigrationIdColumnName))
                .Append(", ")
                .Append(SqlGenerationHelper.DelimitIdentifier(ProductVersionColumnName))
                .Append(", [ContextKey], [Model])")
                .Append("VALUES (")
                .Append(stringTypeMapping.GenerateSqlLiteral(row.MigrationId))
                .Append(", ")
                .Append(stringTypeMapping.GenerateSqlLiteral(row.ProductVersion))
                .Append($", 'ContextConstants.ContextName.ContextConstants.ContextSchemaName', 0x)")
                .AppendLine(SqlGenerationHelper.StatementTerminator)
                .ToString();




                Here is a link to the source code on github:
                https://github.com/aspnet/EntityFrameworkCore/blob/master/src/EFCore.Relational/Migrations/HistoryRepository.cs







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 25 at 16:41









                GaryGary

                112 bronze badges




                112 bronze badges
















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55342435%2fhow-to-customize-migration-history-table-with-entity-framework-core%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현