Search code examples
c#entity-frameworkentity-framework-coreazure-functionsef-core-6.0

EF Core DbContext in Azure Functions with Repository


I've an Azure Function App with multiple Azure functions and EF Core 6.

In the Startup.cs I add the repository with AddScoped and pass the connectionString.

class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        string connectionString = Environment.GetEnvironmentVariable("SqlConnectionString");
        builder.Services.AddScoped<SQLRepository>(x => ActivatorUtilities.CreateInstance<SQLRepository>(x, connectionString));
    }
}

The repository itself create the dbContext and initiate the migration.

public class SQLRepository
{
    private readonly MyDBContext _context;

    public SQLRepository(String connectionString)
    {
        var options = new DbContextOptionsBuilder<MyDBContext>().UseSqlServer(connectionString).Options;            
        _context = new MyDBContext(options);
        _context.Database.Migrate();
    }
}

But since the Configure in Startup is called twice (once for each Azure function) the second time the repository is created, I get the error, the object __EFMigrationsHistory exists. Maybe, because the first migration is still in progress as the second try is started.

Is there a way to prevent this? Or do I have to perform the migration in an extra Azure function that is only called on start once?


Solution

  • Inspired by EF Core Migrations in Azure Function startup I use a custom IWebJobsStartup and perform the migration there and not in the SQLRepository itself.