rardav
rardav

Reputation: 43

Containerized .NET Api, Database.Migrate() not creating migrations

Sorry if the question might seem stupid, I am still learning docker, containers and .NET. I have a SQL Server db configured in a docker container with a .NET Web Api in another container, both started with a docker-compose. I configured my database to perform automatic migrations. My problem is that migrations are not created whenever I do changes in any entity. I also tried doing update-database manually, but I cannot since I am starting docker-compose using Visual Studio and apparently the Startup project needs to be an Api (Users.Api in my case). If I set Users.Api as the Startup project, I do not have a running database container, so the operation cannot connect to the db.

Snippet of docker-compose

  usersdb:
    container_name: usersdb
    restart: always
    user: root
    environment:
      SA_PASSWORD: aCertainPassword
      ACCEPT_EULA: Y
    ports:
      - "1433:1433"
    volumes:
      - users_data:/var/opt/mssql/data
  users.api:
    container_name: users.api
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
    depends_on:
      - usersdb
    ports:
      - "8300:80"

Here is my project structure enter image description here

And here I have the Program.cs

using Microsoft.EntityFrameworkCore;
using Users.Infrastructure.Extensions;
using Users.Infrastucture.Contexts;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

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

builder.Services.AddAutoMapper();
builder.Services.AddRepositories();

builder.Services.AddDbContext<UsersContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();

var app = builder.Build();

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

using (var scope = app.Services.CreateScope())
{
    var dataContext = scope.ServiceProvider.GetRequiredService<UsersContext>();
    dataContext.Database.Migrate();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

Upvotes: 1

Views: 258

Answers (1)

rardav
rardav

Reputation: 43

One work around for this was to just start my containers in detached mode and add the migrations manually myself through Visual Studio. I will not mark this as the right answer since maybe somebody else has a better way to do it.

Upvotes: 2

Related Questions