Skip to content

Instantly share code, notes, and snippets.

Last active January 10, 2023 15:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
MySqlMigrationSqlGenerator Example

MySqlMigrationSqlGenerator Example

dotnet add package MySql.Data.EntityFramework
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Migrations.Builders;
using System.Data.Entity.Migrations.Model;
using System.Text.RegularExpressions;
using DbUp;
using Demo;
using MySql.Data.EntityFramework;
using MySql.Data.MySqlClient;

// Fix:  No Entity Framework provider found for the ADO.NET provider with invariant name 'MySql.Data.MySqlClient'
DbConfiguration.SetConfiguration(new MyDbConfiguration());

var createTableOperation = new CreateTableOperation("customers");

var createTable = new CreateTableOperation("customers");

    new ColumnModel(PrimitiveTypeKind.Int64)
        Name = "id",
        StoreType = "int",
        IsIdentity = true,
        IsNullable = false,

createTable.Columns.Add(new ColumnModel(PrimitiveTypeKind.String)
    Name = "name",
    StoreType = "varchar",
    MaxLength = 45,
    DefaultValue = null,

createTable.PrimaryKey = new AddPrimaryKeyOperation();

var sqlGenerator = new MySqlMigrationSqlGenerator();

var sqlStatements = sqlGenerator.Generate(
    new[] { createTableOperation }, "MySql.Data.MySqlClient"

// Return the first SQL statement as a string
foreach (var sqlStatement in sqlStatements)
    var sql = sqlStatement.Sql.ToString();


create table `customers` (`id` int unsigned not null  auto_increment ,`name` varchar(45) , KEY (`id`)) engine=InnoDb auto_increment=0;
namespace Demo;

using System.Data.Entity;
using System.Data.Entity.Migrations;
using MySql.Data.MySqlClient;

public class MyDbConfiguration : DbConfiguration
    public MyDbConfiguration()
        // Set the provider services for the MySql .NET connector
        SetProviderServices("MySql.Data.MySqlClient", new MySqlProviderServices());
        SetProviderFactory("MySql.Data.MySqlClient", MySqlClientFactory.Instance);


public class MyDbContext : DbContext
    // Your DbContext code here

public class Columns
    public object Foo { get; set; }
    public object Bar { get; set; }

public class TestMigration : DbMigration
    public override void Up()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment