0
0
Files
Extensions.Configuration.En…/RAIC.Extensions.Configuration.EntityFrameworkCore/README.md

2.1 KiB

RAIC.Extensions.Configuration.EntityFrameworkCore

This library is a Microsoft.Extensions.Configuration.IConfigurationProvider that reads settings from a DbSet<ISetting> Settings property present on your Entity Framework Core DbContext.

Goals

  1. Usable with minimal constraints on your entity model
  2. Follows conventional configuration patterns
  3. IOptionsMonitor update support through optional opt-in services (see RAIC.Extensions.Configuration.EntityFrameworkCore.PostgreSQL & RAIC.Extensions.Configuration.EntityFrameworkCore.SqlServer)

Requirements

  • .NET 8

Gotchas

  • Setting values cannot be null (as signified by the RequiredAttribute on ISetting.Value)
  • Setting keys should not contain the = character (similar to CommandLineConfigurationProvider & EnvironmentVariablesConfigurationProvider)

Usage Example


using RAIC.Extensions.Configuration.EntityFrameworkCore.Extensions;

public record Setting : ISetting
{
    [Key]
    public required string Key { get; set; }

    [Required]
    public required string Value { get; set; }
}

public class MyDbContext(DbContextOptions<MyDbContext> options) : DbContext(options), ISettingsDbContext<DbSet<Setting>, Setting>, ISettingsDbContextFactory<MyDbContext>
{
    public DbSet<Setting> Settings { get; set; }

    public static MyDbContext Create(DbContextOptions<MyDbContext> options) => new(options);
}

var builder =  Host.CreateApplicationBuilder(args) // or  WebApplication.CreateBuilder(args); 

// build an initial configuration
builder.Configuration.AddJsonFile("appsettings.json")
                     .AddUserSecrets<Program>(); // or whereever your connection string lives

// obtain connection string from preliminary config so can initialise other settings from DbSet
builder.Configuration.AddDbSet<MyDbContext, Setting>(dbContextOptions => dbContextOptions.UseNpgsql(builder.Configuration.GetConnectionString("Default")));

...

await builder.Build().RunAsync(); // use config as normal

Read more about Configuration on the Microsoft Docs site.