Db2Code–part 6 – implementation details

Problem 1 More dbContexts

I have think that a user can have more than 1 DBContext / database implemented. If there was just only one , it were easy to add a partial to program.cs and register the database DI

services.AddDbContext<ApplicationDBContext>

in the partial .  However, if each database is generated, how to have this  ? The answer is   https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.moduleinitializerattribute?view=net-7.0

[ModuleInitializer]
    public static void AddMe()
    {
        Generated.UtilsControllers.registerContexts.Add(new RegisterApplicationDBContext());
    }

And in the WebAPI

foreach (IRegisterContext item in UtilsControllers.registerContexts)
         {
            typesContext.Add( item.AddServices(builder.Services, builder.Configuration));
         }

Problem 2 Create database if not exists

I want to let the user to create the database if it dows not exists. But how, if I do not know the name of the database ? The idea is to obtain the DBContext from the name and inject into the DI

builder.Services.AddTransient((ctx) =>
         {
             Func<string, DbContext?> a = (string dbName) =>
             {
                 var t = typesContext.First(it => it.Name == dbName);
                
                 var req = ctx.GetRequiredService(t);
                 if (req == null) return null;
                 return req as DbContext;
             };
             return a;
         });

And then obtain from the controller action

[HttpPost(“{dbName}”)]
    public async Task<bool> EnsureCreated([FromServices] Func<string, DbContext?> fact, string dbName)
    {
        var exists = AllDB.Singleton.ExistsDB(dbName);
        if (!exists)
        {
            throw new ArgumentException(“DB does not exists ” + dbName);
        }

       var req = fact(dbName);
        if(req == null)
            throw new ArgumentException(“service does not exists ” + dbName);

       return await req.Database.EnsureCreatedAsync();
    }

Problem 3 ; Generate the correct pasca case names for typescript properties

This was something difficult. But  –  I solved by simply add this

public class LowerCaseNamingPolicy : JsonNamingPolicy
{
    public override string ConvertName(string name)
    {
        if (string.IsNullOrWhiteSpace(name))
            return name;

        return name.ToLower();
    }
}

in order to have all with lowercase

builder.Services.AddControllers()
             .AddJsonOptions(c =>
             {
                 c.JsonSerializerOptions.PropertyNamingPolicy = new LowerCaseNamingPolicy();
             })
               .PartManager.ApplicationParts.Add(new AssemblyPart(assControllers)); ;
         ;