C
C#2y ago
Denis

✅ Programmatically applying EF migration on startup to MySQL DB in Docker fails

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

const string CONNECTION_STRING = "Server=mysql,uid=root,Database=MyProject";
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(CONNECTION_STRING));

var app = builder.Build();

await using (var scope = app.Services.CreateAsyncScope())
{
var applicationContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await applicationContext.Database.EnsureCreatedAsync().ConfigureAwait(false);
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

const string CONNECTION_STRING = "Server=mysql,uid=root,Database=MyProject";
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseMySQL(CONNECTION_STRING));

var app = builder.Build();

await using (var scope = app.Services.CreateAsyncScope())
{
var applicationContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await applicationContext.Database.EnsureCreatedAsync().ConfigureAwait(false);
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
I'm trying to apply my initial migration on server startup to the connected MySql db. Everything is running via docker-compose. Unfortunately, I'm getting an Argument null exception when attempting to Ensure the database is created - Value cannot be null (Paramater 'Database') Any ideas as to what I'm doing wrong? The Db is empty. I'd assume EF would create the necessary entry for my project
1 Reply
Denis
DenisOP2y ago
Same happens when replacing EnsureCreatedAsync with MigrateAsync My connection string was invalid. I was using , instead of ;
Want results from more Discord servers?
Add your server