Home > database >  How force DbContexts to read from the connection string in the right appsettings
How force DbContexts to read from the connection string in the right appsettings

Time:12-08

I have multiple DbContexts in my project I am using .Net 6 and efCore 6. I am passing connection string to the contexts like this.

public partial class MyContext : DbContext
{    
    public MyContext(DbContextOptions<MyContext> options) : base(options) { }
    public MyContext() : base() { }
}

And in program.cs

services.AddDbContext<MyContext>(options =>
{
     options.UseSqlServer(Configuration.GetSection("MyConnrctionStr").Value);     
});

The problem is I should delegate the creation of my DbContext to a third party library that does not pass connection string to the context. So I should handle setting the right connection string in my dbContext classes themselves. Also the config should come from corresponding environment settings i.e. development, production, debug, ... So that should be something like this:


public partial class MyContext : DbContext
{    
    public MyContext(DbContextOptions<MyContext> options) : base(options) { }
    public MyContext() : base() { }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
        var string connectionStr= //Read ConnectionString From Correct appsettings.json file Regarding to Environment
            optionsBuilder.UseSqlServer(connectionStr);
        }
}

How can I achieve that?

CodePudding user response:

You can have current environment name in the class and then read the appsetting.[currentenvironment].json with some code like this.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(getConnectionString());
    }
    private static string getConnectionString()
    {
        var environmentName =
          Environment.GetEnvironmentVariable(
              "ASPNETCORE_ENVIRONMENT");

        var config = new ConfigurationBuilder().AddJsonFile("appsettings"   (String.IsNullOrWhiteSpace(environmentName) ? "" : "."   environmentName)   ".json", false).Build();
        return config.GetConnectionString("DefaultConnection");
    }

This way you do not need to send any thing when injecting DBContext, etc. But the name of connection string would be hard codded inside DbContext

  • Related