3

I have defined a connection string in the appsettings.json file. now I want to read it in my TextDBConext file, how can I do it?

public class TestContext: DbContext
    {
        public DbSet<TestTable> TestTable { get; set; }
        public TestContext()
        {
        }
        public IConfiguration Configuration { get; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Connection string"); //I have hardcoded here, but I want from appsettings.json
        }
    }

Appsettings.json file:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "connection_string": "Connection String"
  }
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • 4
    Does this answer your question? [Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App](https://stackoverflow.com/questions/45796776/get-connectionstring-from-appsettings-json-instead-of-being-hardcoded-in-net-co) – Ryan Sparks Dec 27 '19 at 10:53
  • https://stackoverflow.com/questions/55566872/create-3-tier-architecture-in-dotnet-core-2-2-web-api-c-sharp/55567348#55567348 check section set connection string – Imran Arshad Dec 27 '19 at 10:53
  • Have a look [read connectionstring outside startup from appsetting.json](https://stackoverflow.com/questions/34269106/read-connectionstring-outside-startup-from-appsetting-json-in-vnext) – mmushtaq Dec 27 '19 at 10:54

2 Answers2

7

You can setup your db context in the startup file and not override OnConfiguring at all. Just add a constructor that takes DbContextOptions<TContext> to your DbContext class. This constructor should pass on the parameter to the base class' constructor, then call AddDbContext<TContext> in your Startup.Configure as follows:

// your TestContext showing constructor
public class TestContext : DbContext
{
    public TestContext(DbContextOptions<TestContext> options) : base(options){ }
}

// Then in Startup.cs
public class Startup
{
   public IConfiguration Configuration {get;}

   public Startup(IConfiguration configuration)
   {
      Configuration = configuration;
   }

   public void ConfigureServices(IServiceCollection services)
   {
       services.AddDbContext<TeamsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("connection_string")));
   }
}

Worth noting is that the AddDbContext<TContext> method has overloads that allow setting the service lifetime for the context to Singleton or Transient if you so wish. The default is Scoped.

Gerald Chifanzwa
  • 1,277
  • 7
  • 14
  • Documented by Microsoft here: https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/#constructor-argument – Peheje Dec 27 '20 at 15:27
3

You can inject IConfiguration into TestContext constructor and then use GetConnectionString(string name) method to get the connection string.

So..

public class TestContext : DbContext
{
    private readonly IConfiguration _configuration;

    public TestContext(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(_configuration.GetConnectionString("Your Connection String Name"));
    }
}
Izzy
  • 6,740
  • 7
  • 40
  • 84
  • but how to pass configuration in the TestContext constructor while initializing? – Vivek Nuna Dec 27 '19 at 10:59
  • 3
    This is the job of the dependency injection system that you should have setup in your Startup.cs file – Steve Dec 27 '19 at 11:01
  • @Steve unfortunately, my _configuration object returns null even though I am calling AddSingleton(Configuration) in Startup.cs. Any idea? – Junaid Nov 01 '20 at 04:38