我有一个具有两个数据库连接的 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 在启动运行后设置连接字符串
发布评论