EntityFramework Core MySQL Script-Migration export customization

c# entity-framework entity-framework-core mysql

Question

When I run Script-Migration in my project that uses EntityFramework Core 2 and MySql, it produces the right set of statements but out of 200 statements, only 5 missing ending semicolon. I already found solutions to override MySqlMigrationSqlGenerator configuration in EntityFramework 6 in the following link:EF6 MySql: Update-Database -Script generates SQL without semicolon , I was wondering about the EF core implementation

1
0
7/17/2019 1:49:59 PM

Accepted Answer

EF core implementation is similar with some difference in overriding Generate method, here is the implementation for CustomMySqlMigrationSqlGenerator:

using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Metadata;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.EntityFrameworkCore.Storage;
namespace test
{
/// <summary>
/// Custom MigrationSqlGenerator to add semi-colons to the end of 
/// all migration statements.
/// </summary>
public class CustomMySqlMigrationSqlGenerator : MySqlMigrationsSqlGenerator
{
    private readonly MigrationsSqlGeneratorDependencies _dependencies;

    public CustomMySqlMigrationSqlGenerator(MigrationsSqlGeneratorDependencies dependencies, 
        IMigrationsAnnotationProvider migrationsAnnotations, 
        IMySqlOptions options): base(dependencies, migrationsAnnotations, options)
    {
        _dependencies = dependencies;
    }

    public override IReadOnlyList<MigrationCommand> Generate(IReadOnlyList<MigrationOperation> operations, IModel model = null)
    {
        List<MigrationCommand> result = new List<MigrationCommand>();
        IEnumerable<MigrationCommand> statements = base.Generate(operations, model);
        foreach (MigrationCommand statement in statements)
        {
            var factory = _dependencies.CommandBuilderFactory.Create();
            factory.Append((statement.CommandText.TrimEnd() + ";").Replace(";;", ";"));
            result.Add(new MigrationCommand(factory.Build(), statement.TransactionSuppressed));
        }
        return result;
    }
  }
}

Also you need to set the configuration in your DbContext:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.ReplaceService<IMigrationsSqlGenerator, CustomMySqlMigrationSqlGenerator>();
    }
0
6/13/2019 6:16:18 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow