I cannot retrieve connection string in DbContext c

2019-09-19 18:36发布

问题:

In Startup.cs Configure Services this works:

var connection = Configuration["ConnectionStrings:DefaultConnection"];

        services.AddDbContext<MyDbContext>(
                 options => { options.UseSqlServer(connection); });

In my MyDbContext.cs class this doesn't work:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

using OESAC.Models;

namespace OESAC.Models
{
    public class MyDbContext : DbContext
    {
        public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
        { }

        public DbSet<Courses> Courses { get; set; }
        public DbSet<Sponsors> Sponsors{ get; set; }

        public IConfiguration Configuration { get; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

           var connection = Configuration["ConnectionStrings:DefaultConnection"];

            optionsBuilder.UseSqlServer(connection);

            ;
        }


    }
}

I can hardcode the connection string but I want it to dynamically change based on my appSettings.Development.json and appSettngs.json (production). I can't believe the time I've spent trying to figure this out. It has cost me way over what I am being paid.

回答1:

You need to inject IConfiguration in constructor to have an access to configuration.

public class MyDbContext : DbContext
{
    private readonly IConfiguration _configuration;

    public MyDbContext(IConfiguration configuration)       
    {
       _configuration = configuration
    }

    public DbSet<Courses> Courses { get; set; }
    public DbSet<Sponsors> Sponsors{ get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {

       var connection = _configuration["ConnectionStrings:DefaultConnection"];

        optionsBuilder.UseSqlServer(connection);            
    }
}

Startup.cs:

services.AddDbContext<ApplicationDbContext>();