| [ea40556] | 1 | using iknow_api.Models;
|
|---|
| 2 | using Npgsql;
|
|---|
| 3 |
|
|---|
| 4 | namespace iknow_api.Data
|
|---|
| 5 | {
|
|---|
| 6 | /// <summary>
|
|---|
| 7 | /// Maps CLR enum member names onto the labels declared in sql/ddl.sql.
|
|---|
| 8 | /// Most labels are just the lowercased member name; the ones that are not
|
|---|
| 9 | /// (UserRole.Professor -> 'prof', Grade.Ten -> '10') are listed explicitly.
|
|---|
| 10 | ///
|
|---|
| 11 | /// The instances are static on purpose. EF Core caches its internal service
|
|---|
| 12 | /// provider against the DbContext options, and a fresh translator instance
|
|---|
| 13 | /// on every resolution makes each set of options look different - EF then
|
|---|
| 14 | /// builds a new provider per resolution and throws
|
|---|
| 15 | /// ManyServiceProvidersCreatedWarning once it has built twenty.
|
|---|
| 16 | /// </summary>
|
|---|
| 17 | public sealed class PgEnumLabels : INpgsqlNameTranslator
|
|---|
| 18 | {
|
|---|
| 19 | public static readonly PgEnumLabels UserRole = new(
|
|---|
| 20 | new Dictionary<string, string>
|
|---|
| 21 | {
|
|---|
| 22 | [nameof(Models.UserRole.Admin)] = "admin",
|
|---|
| 23 | [nameof(Models.UserRole.Professor)] = "prof",
|
|---|
| 24 | [nameof(Models.UserRole.Student)] = "student",
|
|---|
| 25 | });
|
|---|
| 26 |
|
|---|
| 27 | public static readonly PgEnumLabels Grade = new(
|
|---|
| 28 | new Dictionary<string, string>
|
|---|
| 29 | {
|
|---|
| 30 | [nameof(Models.Grade.Six)] = "6",
|
|---|
| 31 | [nameof(Models.Grade.Seven)] = "7",
|
|---|
| 32 | [nameof(Models.Grade.Eight)] = "8",
|
|---|
| 33 | [nameof(Models.Grade.Nine)] = "9",
|
|---|
| 34 | [nameof(Models.Grade.Ten)] = "10",
|
|---|
| 35 | });
|
|---|
| 36 |
|
|---|
| 37 | /// <summary>Lowercases the member name, which is all the other enums need.</summary>
|
|---|
| 38 | public static readonly PgEnumLabels Lowercase = new(new Dictionary<string, string>());
|
|---|
| 39 |
|
|---|
| 40 | private readonly IReadOnlyDictionary<string, string> _labels;
|
|---|
| 41 |
|
|---|
| 42 | private PgEnumLabels(IReadOnlyDictionary<string, string> labels) => _labels = labels;
|
|---|
| 43 |
|
|---|
| 44 | public string TranslateTypeName(string clrName) => clrName;
|
|---|
| 45 |
|
|---|
| 46 | public string TranslateMemberName(string clrName) =>
|
|---|
| 47 | _labels.TryGetValue(clrName, out var label) ? label : clrName.ToLowerInvariant();
|
|---|
| 48 | }
|
|---|
| 49 | }
|
|---|