I cannot retrieve connection string in DbContext class in .NET Core 2.2 Razor Pages

好久不见. 提交于 2019-12-25 17:20: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>();


来源:https://stackoverflow.com/questions/56178017/i-cannot-retrieve-connection-string-in-dbcontext-class-in-net-core-2-2-razor-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!