Home:ALL Converter>EF Dotnet Core - Setting connection string after solution running

EF Dotnet Core - Setting connection string after solution running

Ask Time:2019-05-04T15:00:17         Author:si2030

Json Formatter

I wrote this question because I wanted to find out how to create a DbContext where you only know the connection string after a user has been authenticated (connection string part of the user detail in a catalog database). My problem was that I cant set this in startup service as I have to wait for the user to log in.

I got an answer that suggested This:

    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
    }

Camilo Terevinto commented on this saying that this is a really terrible suggestion saying:

Using AddDbContext, EF Core uses a factory behind to decide when new instances are created

I have noted that this option (answer) is actually in the EF Docs under "Constructor Argument".

If its in the docs and appears to be the only way I can run create a connection after a user logs in is it OK? Is there a better way? Are there things I need to be aware of etc.. Wondering if someone can elaborate on Camilo's comment.

Author:si2030,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/55980313/ef-dotnet-core-setting-connection-string-after-solution-running
yy