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.