我无法在.NET Core 2.2 Razor页面的DbContext类中检索连接字符串 [英] I cannot retrieve connection string in DbContext class in .NET Core 2.2 Razor Pages
本文介绍了我无法在.NET Core 2.2 Razor页面的DbContext类中检索连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Startup.cs配置服务中有效:
var connection = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<MyDbContext>(
options => { options.UseSqlServer(connection); });
在MyDbContext.cs类中,此操作无效:
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);
;
}
}
}
我可以对连接字符串进行硬编码,但是我希望它根据我的appSettings.Development.json和appSettngs.json(生产)进行动态更改。我不敢相信我花了很多时间来解决这个问题。它使我无法获得应得的报酬。
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.
推荐答案
您需要在构造函数中注入 IConfiguration
才能访问
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:
Startup.cs:
services.AddDbContext<ApplicationDbContext>();
这篇关于我无法在.NET Core 2.2 Razor页面的DbContext类中检索连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文