/NpgsqlSourceGenerators

Register enums for use with NpgSQL easily

Primary LanguageC#MIT LicenseMIT

NuGet Version NuGet Downloads GitHub Actions Workflow Status GitHub License

Npgsql Source Generators

Registering all enums one by one is tedious. Use this.

Usage

namespace MyCoolApp;

[PostgresEnum]
public enum Status {
    Completed,
    InProgress,
    Started,
    Queued
}

[PostgresEnum(Name = "process_priority")]
public enum Priority {
    High,
    Medium,
    Low
}

will generate the following code:

// <auto-generated/>
#nullable enable
using Npgsql;
using Microsoft.EntityFrameworkCore;
       
namespace NpgSqlGenerators;

internal static class PostgresEnumHelpers
{
    /// <summary>
    /// Calls <see cref="Npgsql.NpgsqlDataSourceBuilder.MapEnum{T}"/> on selected enums
    /// </summary>
    public static NpgsqlDataSourceBuilder MapPostgresEnums(this NpgsqlDataSourceBuilder builder)
    {
        builder.MapEnum<MyCoolApp.Status>();
        builder.MapEnum<MyCoolApp.Priority>(pgName: "process_priority");
        return builder;
    }

    /// <summary>
    /// Calls <see cref="Microsoft.EntityFrameworkCore.NpgsqlModelBuilderExtensions.HasPostgresEnum{T}"/> on selected enums
    /// </summary>
    public static void RegisterPostgresEnums(this ModelBuilder builder)
    {
        builder.HasPostgresEnum<MyCoolApp.Status>();
        builder.HasPostgresEnum<MyCoolApp.Priority>(name: "process_priority");
    }
}

which can be used, for example, like so:

var source = new NpgsqlDataSourceBuilder(connectionString).npgSourceBuilder
    .MapPostgresEnums()
    .Build();
services.AddDbContext<MyDbContext>(options => options.UseNpgsql(source));
public class MyDbContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        builder.RegisterPostgresEnums();
    }    
}