如何从Asp.Net Core中的DBContext文件中的appsettings.json中读取连接字符串? [英] How to read connection string from appsettings.json in a DBContext file in Asp.Net Core?
问题描述
我在appsettings.json文件中定义了一个连接字符串.现在我想在我的TextDBConext文件中阅读它,该怎么办?
I have defined a connection string in the appsettings.json file. now I want to read it in my TextDBConext file, how can I do it?
public class TestContext: DbContext
{
public DbSet<TestTable> TestTable { get; set; }
public TestContext()
{
}
public IConfiguration Configuration { get; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Connection string"); //I have hardcoded here, but I want from appsettings.json
}
}
Appsettings.json文件:
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"connection_string": "Connection String"
}
}
推荐答案
您可以在启动文件中设置数据库上下文,而完全不覆盖 OnConfiguring
.只需在DbContext类中添加采用 DbContextOptions< TContext>
的构造函数即可.此构造函数应将参数传递给 base
类的构造函数,然后在 Startup.Configure
中调用 AddDbContext< TContext>
,如下所示:
You can setup your db context in the startup file and not override OnConfiguring
at all.
Just add a constructor that takes DbContextOptions<TContext>
to your DbContext class. This constructor should pass on the parameter to the base
class' constructor,
then call AddDbContext<TContext>
in your Startup.Configure
as follows:
// your TestContext showing constructor
public class TestContext : DbContext
{
public TestContext(DbContextOptions<TestContext> options) : base(options){ }
}
// Then in Startup.cs
public class Startup
{
public IConfiguration Configuration {get;}
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TeamsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("connection_string")));
}
}
值得注意的是, AddDbContext< TContext>
方法具有重载功能,允许您根据需要将上下文的服务寿命设置为Singleton或Transient.默认值为作用域".
Worth noting is that the AddDbContext<TContext>
method has overloads that allow setting the service lifetime for the context to Singleton or Transient if you so wish. The default is Scoped.
这篇关于如何从Asp.Net Core中的DBContext文件中的appsettings.json中读取连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!