如何从Asp.Net Core中的DBContext文件中的appsettings.json中读取连接字符串?

编程入门 行业动态 更新时间:2024-10-24 10:20:30
本文介绍了如何从Asp.Net Core中的DBContext文件中的appsettings.json中读取连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在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中读取连接字符串?

本文发布于:2023-11-02 14:59:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552704.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   文件   Core   Asp   Net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!