DotNet Core 在启动运行后设置连接字符串

编程入门 行业动态 更新时间:2024-10-28 19:20:54
本文介绍了DotNet Core 在启动运行后设置连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个具有两个数据库连接的 Visual Studio 解决方案.第一个是保存用户名密码和数据库的目录.第二个将是用户数据.我可以在ConfigureServices"中设置目录数据库的连接,这很好.一旦用户尝试登录并成功,我就可以知道用户将连接到的数据库.

I have a Visual Studio solution that has two database connections. The first is a catalog holding username password and database. The second will be the users data. I can set up the connection for the catalog database in "ConfigureServices" and thats fine. Once the user has attempted to log in and succeeded I can then know the database the user will connect to.

我的问题是,如何在启动运行后创建服务..如何在正常操作过程中使用连接字符串添加DBcontext.根据我的搜索,如果您知道启动时的连接字符串就可以了..

My problem is, How do I create the service after startup has run.. how do I use the connection string to add a DBcontext in the normal course of operations. From my searches this is OK if you know the connection string at start up..

var connection = @"Server=(localdb)mssqllocaldb;Database=JobsLedgerDB;Trusted_Connection=True;ConnectRetryCount=0"; services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));

但是如果我在启动时没有连接字符串...当我终于有了连接字符串时,如何在项目已经启动并运行后添加服务?

But if I dont have a connection string at startup... How do I add a service after the project is already up and running when I finally do have the connection string?

推荐答案

您可以在应用程序的每个类中实例化 DbContext.

You can instantiate your DbContext in every class of your application.

检查文档:配置 DbContext

示例

var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>(); optionsBuilder.UseSqlite("Data Source=blog.db"); using (var context = new BloggingContext(optionsBuilder.Options)) { // do stuff }

对于您的 SQL 连接

For your SQL Connection

var connection = @"Server=(localdb)mssqllocaldb;Database=JobsLedgerDB;Trusted_Connection=True;ConnectRetryCount=0"; var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>(); optionsBuilder.UseSqlServer(connection); using (var context = new BloggingContext(optionsBuilder.Options)) { // do stuff }

更多推荐

DotNet Core 在启动运行后设置连接字符串

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

发布评论

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

>www.elefans.com

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