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
Add a comment
|
1 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>();
}
-
I have tested this code with Entity Framework Core 5.0.5 and Pomelo.EntityFramework.MySql 5.0.0 but I got this error when I executed “Script-Migration -context MyDbContext --idempotent”: Unable to resolve service for type 'Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal.IMySqlOptions' while attempting to activate 'MT4.WebManager.API.HelperClasses.CustomMySqlMigrationSqlGenerator'. Would you help me? Jun 14, 2021 at 4:37