Skip to content

refactor(data): improve seeding with UseAsyncSeeding #197

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

Merged
merged 1 commit into from
Apr 7, 2025
Merged
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
26 changes: 8 additions & 18 deletions Dotnet.Samples.AspNetCore.WebApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Dotnet.Samples.AspNetCore.WebApi.Data;
using Dotnet.Samples.AspNetCore.WebApi.Mappings;
using Dotnet.Samples.AspNetCore.WebApi.Services;
using Dotnet.Samples.AspNetCore.WebApi.Utilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Serilog;
Expand All @@ -20,26 +21,22 @@
* Logging
* -------------------------------------------------------------------------- */
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(builder.Configuration).CreateLogger();

builder.Host.UseSerilog();

/* -----------------------------------------------------------------------------
* Services
* -------------------------------------------------------------------------- */

builder.Services.AddControllers();

var dataSource =
$"{AppDomain.CurrentDomain.SetupInformation.ApplicationBase}/Data/players-sqlite3.db";

builder.Services.AddDbContextPool<PlayerDbContext>(options =>
{
var dataSource = Path.Combine(AppContext.BaseDirectory, "Data", "players-sqlite3.db");
options.UseSqlite($"Data Source={dataSource}");

if (builder.Environment.IsDevelopment())
{
options.EnableSensitiveDataLogging();
options.LogTo(Console.WriteLine, LogLevel.Information);
options.LogTo(Log.Logger.Information, LogLevel.Information);
// https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-9.0/whatsnew#improved-data-seeding
options.UseAsyncSeeding(DbContextUtils.SeedAsync);
}
});

Expand Down Expand Up @@ -84,16 +81,16 @@
* Middlewares
* https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware
* -------------------------------------------------------------------------- */

app.UseSerilogRequestLogging();

if (app.Environment.IsDevelopment())
{
// https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle
app.UseSwagger();
app.UseSwaggerUI();
}

// https://github.com/serilog/serilog-aspnetcore
app.UseSerilogRequestLogging();

// https://learn.microsoft.com/en-us/aspnet/core/security/enforcing-ssl
app.UseHttpsRedirection();

Expand All @@ -103,11 +100,4 @@
// https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing#endpoints
app.MapControllers();

/* -----------------------------------------------------------------------------
* Data Seeding
* https://learn.microsoft.com/en-us/ef/core/modeling/data-seeding
* -------------------------------------------------------------------------- */

app.SeedDbContext();

await app.RunAsync();
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
namespace Dotnet.Samples.AspNetCore.WebApi.Data;
using Dotnet.Samples.AspNetCore.WebApi.Data;
using Microsoft.EntityFrameworkCore;

namespace Dotnet.Samples.AspNetCore.WebApi.Utilities;

public static class ApplicationBuilderExtensions
{
/// <summary>
/// Simple extension method to populate the database with an initial set of data.
/// Async extension method to populate the database with initial data
/// </summary>
public static void SeedDbContext(this IApplicationBuilder app)
public static async Task SeedDbContextAsync(this IApplicationBuilder app)
{
using var scope = app.ApplicationServices.CreateScope();
var dbContext = scope.ServiceProvider.GetService<PlayerDbContext>();
var services = scope.ServiceProvider;
var logger = services.GetRequiredService<ILogger<Program>>();
var dbContext = services.GetRequiredService<PlayerDbContext>();

if (dbContext != null)
try
{
// https://learn.microsoft.com/en-us/ef/core/managing-schemas/ensure-created
dbContext.Database.EnsureCreated();
await dbContext.Database.EnsureCreatedAsync();

if (!dbContext.Players.Any())
if (!await dbContext.Players.AnyAsync())
{
dbContext.Players.AddRange(PlayerData.CreateStarting11());
await dbContext.Players.AddRangeAsync(PlayerData.CreateStarting11());
await dbContext.SaveChangesAsync();
logger.LogInformation("Successfully seeded database with initial data.");
}
}
catch (Exception exception)
{
logger.LogError(exception, "An error occurred while seeding the database");
throw new InvalidOperationException(
"An error occurred while seeding the database",
exception
);
}
}
}
42 changes: 42 additions & 0 deletions Dotnet.Samples.AspNetCore.WebApi/Utilities/DbContextUtils.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using Dotnet.Samples.AspNetCore.WebApi.Data;
using Microsoft.EntityFrameworkCore;

namespace Dotnet.Samples.AspNetCore.WebApi.Utilities;

public static class DbContextUtils
{
/// <summary>
/// Seeds the database with initial data if empty.
/// </summary>
/// <remarks>
/// This method checks if the database is empty and seeds it with initial data.
/// It is designed to be used with UseAsyncSeeding.
/// </remarks>
/// <param name="context">The database context to seed.</param>
/// <param name="_">Unused parameter, required by the UseAsyncSeeding API.</param>
/// <param name="cancellationToken">A token to cancel the operation if needed.</param>
/// <returns>A task representing the asynchronous seeding operation.</returns>
public static Task SeedAsync(DbContext context, bool _, CancellationToken cancellationToken)
{
if (context is not PlayerDbContext playerDbContext)
{
throw new ArgumentException(
$"Expected context of type {nameof(PlayerDbContext)}, but got {context.GetType().Name}",
nameof(context)
);
}
return SeedPlayersAsync(playerDbContext, cancellationToken);
}

private static async Task SeedPlayersAsync(
PlayerDbContext dbContext,
CancellationToken cancellationToken
)
{
if (!await dbContext.Players.AnyAsync(cancellationToken))
{
await dbContext.Players.AddRangeAsync(PlayerData.CreateStarting11(), cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
}
}
}
23 changes: 0 additions & 23 deletions Dotnet.Samples.AspNetCore.WebApi/Utilities/PlayerDataExtensions.cs

This file was deleted.

Loading