Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...