40 lines
1.3 KiB
C#
40 lines
1.3 KiB
C#
using FictionArchive.Service.Shared.Services.Database;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Npgsql;
|
|
|
|
namespace FictionArchive.Service.Shared.Extensions;
|
|
|
|
public static class DatabaseExtensions
|
|
{
|
|
public static IServiceCollection RegisterDbContext<TContext>(
|
|
this IServiceCollection services,
|
|
string connectionString,
|
|
bool skipInfrastructure = false) where TContext : FictionArchiveDbContext
|
|
{
|
|
if (skipInfrastructure)
|
|
{
|
|
// For schema export: use in-memory provider to allow EF Core entity discovery
|
|
services.AddDbContext<TContext>(options =>
|
|
{
|
|
options.UseInMemoryDatabase($"SchemaExport_{typeof(TContext).Name}");
|
|
});
|
|
}
|
|
else
|
|
{
|
|
var dataSourceBuilder = new Npgsql.NpgsqlDataSourceBuilder(connectionString);
|
|
dataSourceBuilder.UseNodaTime();
|
|
dataSourceBuilder.UseJsonNet();
|
|
var dataSource = dataSourceBuilder.Build();
|
|
|
|
services.AddDbContext<TContext>(options =>
|
|
{
|
|
options.UseNpgsql(dataSource, o =>
|
|
{
|
|
o.UseNodaTime();
|
|
});
|
|
});
|
|
}
|
|
return services;
|
|
}
|
|
} |