0

I'm trying to change schema dynamically. Everytime a login happens I need to check, set, and if necessary change the schema to make my queries with Entity.

I found a question with the perfect solution but I'm trying to use this with Npgsql and I didn't find a way.

See the link below:

Dynamically changing schema in Entity Framework Core

My code till now:

        public WebAppSchemaContext(DbContextOptions<WebAppSchemaContext> options, IConfiguration configuration) : base(options)
    {
        _configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseNpgsql(_configuration.GetConnectionString("DefaultConnection"));
// here I don't know what to do with Npgsql
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Pais>().ToTable("pais", Util.Schema);
        ...

Everytime a login happens:

        public Login? ObterUsuarioPorCpf(string cpf, string empresa)
    {
        var empresaUser = webAppContext
            .Set<Company>()
            .FirstOrDefault(x => x.Empresa == empresa);

        if (empresaUser == null)
            return null;

        Util.Schema = "emp" + empresaUser.Empresa;

And to do the queries I'm doing like this:

            return webAppSchemaContext
            .Set<Pais>()
            .Select(p => new PaisDto
            {
                Codigo = p.NumCode,
                Nome = p.NamePt
            })
            .ToList();

Does anyone knows how I can configure this on Npgsql?

Thanks.

Best regards.

Wilton
  • 218
  • 2
  • 11

0 Answers0