DotNet Core在启动后设置连接字符串 [英] DotNet Core setting the connection string after startup has run

查看:198
本文介绍了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连接

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在启动后设置连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆