要将连接字符串移动到appsettings.json文件中,需要在上下文类中进行哪些更改 [英] What changes need to be made in context class to move connection string into appsettings.json file
本文介绍了要将连接字符串移动到appsettings.json文件中,需要在上下文类中进行哪些更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用.NET核心Web API项目,并且正在尝试将连接字符串移动到appsettings.json文件。
为此,我做了以下更改:
在启动文件中:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy(allowSpecificOrigins,
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddSingleton(provider => Configuration);
services.AddDbContext<pixelleContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("PixelleConnection")));
}
和appsettings.json文件中如下所示:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"PixelleConnection": "Server=localhost;Database=PixelleSpecSheets;Trusted_Connection=True;"
}
}
我不确定需要对我的上下文类、上下文类进行哪些更改,如下所示:
public partial class pixelleContext : DbContext
{
public pixelleContext()
{
}
public pixelleContext(DbContextOptions<pixelleContext> options)
: base(options)
{
}
public virtual DbSet<SpecCol> SpecCol { get; set; }
public virtual DbSet<SpecRow> SpecRow { get; set; }
public virtual DbSet<Specsheet> Specsheet { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
}
}
}
和引发错误的代码:
[System.Web.Http.HttpGet]
public IEnumerable<Specsheet> Get()
{
using (var context = new pixelleContext())
{
return context.Specsheet.ToList();
}
}
推荐答案
您不需要在您的数据库上下文类中执行任何操作,它是正确的
您应该这样调用数据库:
//....
private readonly pixelleContext _context;
public ****Controller(pixelleContext context)
{
_context = context;
}
//....
[HttpGet]
public IEnumerable<Specsheet> Get()
{
var model = _context.Specsheet.ToList();
return model;
}
这篇关于要将连接字符串移动到appsettings.json文件中,需要在上下文类中进行哪些更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文