Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Update Database Seeding Implementation for EF Core 9 Compatibility #1294

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions src/Infrastructure/Data/ApplicationDbContextInitialiser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,23 @@ namespace CleanArchitecture.Infrastructure.Data;

public static class InitialiserExtensions
{
public static void AddAsyncSeeding(this DbContextOptionsBuilder builder, IServiceProvider serviceProvider)
{
builder.UseAsyncSeeding(async (context, _, ct) =>
{
var initialiser = serviceProvider.GetRequiredService<ApplicationDbContextInitialiser>();

await initialiser.SeedAsync();
});
}

public static async Task InitialiseDatabaseAsync(this WebApplication app)
{
using var scope = app.Services.CreateScope();

var initialiser = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitialiser>();

await initialiser.InitialiseAsync();

await initialiser.SeedAsync();
}
}

Expand Down
18 changes: 9 additions & 9 deletions src/Infrastructure/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,22 +25,22 @@ public static void AddInfrastructureServices(this IHostApplicationBuilder builde
{
options.AddInterceptors(sp.GetServices<ISaveChangesInterceptor>());
#if (UsePostgreSQL)
options.UseNpgsql(connectionString);
options.UseNpgsql(connectionString).AddAsyncSeeding(sp);
#elif (UseSqlite)
options.UseSqlite(connectionString);
options.UseSqlite(connectionString).AddAsyncSeeding(sp);
#else
options.UseSqlServer(connectionString);
options.UseSqlServer(connectionString).AddAsyncSeeding(sp);
#endif
});
});

#if (UseAspire)
#if (UsePostgreSQL)
#if (UsePostgreSQL)
builder.EnrichNpgsqlDbContext<ApplicationDbContext>();
#elif (UseSqlServer)
#elif (UseSqlServer)
builder.EnrichSqlServerDbContext<ApplicationDbContext>();
#endif
#endif

#endif

builder.Services.AddScoped<IApplicationDbContext>(provider => provider.GetRequiredService<ApplicationDbContext>());

builder.Services.AddScoped<ApplicationDbContextInitialiser>();
Expand Down