You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

EF Core 6 结合Pomelo.EntityFrameworkCore.MySql无法自动创建数据库问题咨询

EF Core 6 + Pomelo MySQL: Database.Migrate() Throws "Unknown database" Error (Code-First)

Problem Context

You're working with EF Core 6 and Pomelo.EntityFrameworkCore.MySql using the code-first approach. Your DbContext constructor calls Database.Migrate() on initialization, but you hit an error saying "Unknown database 'mydatabase' database does not exist" on the first run—even though migrations should create the database automatically. You've confirmed your MySQL user has admin permissions, so that's not the root of the issue.

Your DbContext code:

public sealed partial class MyDbContext : DbContext { 
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { 
        Database.Migrate(); 
        ChangeTracker.LazyLoadingEnabled = false; 
    }
}

Connection string:

"DbConnection": "server=127.0.0.1;port=3306;database=mydatabase;uid=muusername;pwd=mypassword;"

Root Cause

The core issue is that EF Core's Database.Migrate() requires an active connection to the target database to run migration scripts, but your connection string specifies a database that doesn't exist yet. MySQL rejects the initial connection attempt when the database in the connection string isn't present—so Migrate() never gets the chance to create the database in the first place.

Solution

You need to first create the database (if it doesn't exist) using a connection that targets MySQL's default system database, then run your migrations. Here's how to implement this in your DbContext:

  1. Add a helper method to create the database before running migrations:
public sealed partial class MyDbContext : DbContext 
{ 
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) 
    {
        CreateDatabaseIfNotExists();
        Database.Migrate(); 
        ChangeTracker.LazyLoadingEnabled = false; 
    }

    private void CreateDatabaseIfNotExists()
    {
        var connectionString = Database.GetConnectionString();
        var connectionBuilder = new MySqlConnectionStringBuilder(connectionString);
        var targetDbName = connectionBuilder.Database;

        // Switch to MySQL's default system database to run the CREATE DATABASE command
        connectionBuilder.Database = "mysql";

        using var tempConnection = new MySqlConnection(connectionBuilder.ToString());
        tempConnection.Open();

        using var createDbCommand = tempConnection.CreateCommand();
        // Use backticks to handle database names with special characters
        createDbCommand.CommandText = $"CREATE DATABASE IF NOT EXISTS `{targetDbName}`;";
        createDbCommand.ExecuteNonQuery();
    }
}
  1. Double-check that you have a compatible version of MySqlConnector installed (it's a dependency of Pomelo, but ensure it matches your EF Core 6 version).

Why This Works

By connecting to MySQL's built-in mysql database first, you bypass the requirement to connect to a non-existent target database. The CREATE DATABASE IF NOT EXISTS command safely creates your database (if it doesn't already exist), allowing Database.Migrate() to then connect successfully and apply your schema migrations.

Additional Checks

  • Confirm your Pomelo.EntityFrameworkCore.MySql version is 6.x (matching EF Core 6's major version).
  • Ensure your MySQL server is running and accessible at the specified host and port.

内容的提问来源于stack exchange,提问作者pantonis

火山引擎 最新活动