question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unknown Database Error When Attempting To Create DB Via Code-First Migrations

See original GitHub issue

Steps to reproduce

Program.cs:

var host = CreateHostBuilder(arguments).Build();
using var scope = host.Services
    .GetRequiredService<IServiceScopeFactory>()
    .CreateScope();

var context1 = scope.ServiceProvider.GetRequiredService<ITestContext>();

context1.Database.Migrate();
host.Run();
public static class DbContextRegistrationExtensions
{
    public static void AddDbContexts(
        this IServiceCollection services,
        IConfigurationRoot configuration)
    {
        RegisterDbContext<ITestContext, TestContext>(
            services,
            configuration,
            "TestConnection",
           "Test");
    }

    private static void RegisterDbContext<TInterface, TContext>(
        this IServiceCollection services,
        IConfiguration configuration,
        string connectionStringName,
        string? schemaName = null,
        ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
        where TContext : DbContext, TInterface, IDbContext
    {
        var connectionString = configuration.GetConnectionString(connectionStringName);

        services.AddDbContext<TInterface, TContext>((_, options) =>
        {
            options.ConfigureWarnings(x => x.Ignore(CoreEventId.ManyServiceProvidersCreatedWarning));
            options.UseSnakeCaseNamingConvention();
            options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), x =>
            {
                x.MigrationsAssembly(AssemblyConstants.MigrationsAssembly);
                x.SchemaBehavior(MySqlSchemaBehavior.Translate, (schema, entity) =>
                {
                    return $"{schema.ToLowerInvariant() ?? "dbo"}_{entity.ToLower()}";
                });

                if (!string.IsNullOrWhiteSpace(schemaName))
                {
                    x.MigrationsHistoryTable($"__{schemaName}MigrationsHistory");
                }
            });

            options.EnableSensitiveDataLogging();
            options.ReplaceService<IMigrationsAssembly, CustomMigrationAssembly>();
        }, serviceLifetime);
    }
}
public class TestContext : DbContext, ITestContext
{
    public TestContext(DbContextOptions<TestContext> options)
        : base(options)
    {
    }

    public DbSet<TestReadModel> Tests { get; set; } = null!;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.HasDefaultSchema(DatabaseBoundedContextConstants.Test);
        modelBuilder.ApplyConfiguration(new TestReadModelConfiguration());
    }
}
public class TestReadModelConfiguration : IEntityTypeConfiguration<TestReadModel>
{
    public void Configure(EntityTypeBuilder<TestReadModel> builder)
    {
        builder.HasKey(x => new { x.CustomerId, x.Id })
            .HasName("PK_Test");

        builder.Property(x => x.CustomerId)
            .IsRequired()
            .ValueGeneratedNever();

        builder.Property(x => x.Id)
            .IsRequired()
            .ValueGeneratedNever();

        builder.Property(x => x.Derp)
            .IsRequired(false)
            .IsUnicode(false)
            .HasMaxLength(50);
    }
}

appsettings.json

{
  "ConnectionStrings": {
    "TestConnection": "server=127.0.0.1;port=3306;user=admin;password=Password123!;database=test_database"
  }
}

docker-compose.yml

services:
  some-mariadb:
    image: mariadb:10.7
    container_name: mariadb2
    ports:
      - 3306:3306
    environment:
      - MYSQL_ROOT_PASSWORD=Password123!
      - MYSQL_PASSWORD=Password123!
      - MYSQL_USER=admin
      - MYSQL_DATABASE=master

The issue

Attempting to create a MariaDB schema / database via code-first migrations yields an Unknown database exception.

MySqlConnector.MySqlException (0x80004005): Unknown database 'test_database'
   at MySqlConnector.Core.ResultSet.ReadResultSetHeaderAsync(IOBehavior ioBehavior) in /_/src/MySqlConnector/Core/ResultSet.cs:line 43

Further technical details

MariaDB version: 10.7 (Docker Container) Operating system: MacOS Pomelo.EntityFrameworkCore.MySql version: 6.0.1 Microsoft.AspNetCore.App version: .NET 6

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:9

github_iconTop GitHub Comments

2reactions
thall90commented, Jun 20, 2022

@mguinness @lauxjpn I was actually able to figure out the root cause of this issue. The exception that I was receiving was actually being thrown within the MySqlConnector code (see the call stack below), so once I set Rider to break for user exceptions only, it created the databases with no issues 🤦‍♂️

I apologize for the waste of time, and am very grateful for your help.

Screen Shot 2022-06-17 at 2 46 23 PM

0reactions
lauxjpncommented, Jun 17, 2022

@thall90 Thanks for letting us know! Yeah, the exception is just part of the check, whether the database already exists or not and is caught and processed internally.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Laravel unknown database error during migration
But when I try to apply this migration using php artisan migrate, I get the following error: vagrant@homestead:~/code/blog$ php artisan migrate ...
Read more >
`db-migrate db:create` not working as intended · Issue #468
I ran into this as well when trying to set up a new project using db-migrate. If you remove the database name from...
Read more >
php artisan migrate - Unknown Database error - Laravel ...
So I am looking for the answer that will work today with Laravel 5.7 where in Windows 10, the database is there in...
Read more >
php artisan migrate results in Unknown database : r/laravel
In terminal, php artisan migrate shows following error: Illuminate\Database\QueryException. SQLSTATE[HY000] [1049] Unknown database ...
Read more >
Can't connect DB created by MySQL to Django project
Got an error checking a consistent migration history performed for database connection 'default': (1049, “Unknown database 'storefront'”)
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found