This is a follow up to a question I asked previously, regarding how to make a DBContext work with different connection strings. It turns out such a thing is possible, but I'm not sure how to modify my project to take advantage of it.
The following refers to a project using Entity Framework Core 6.0.7, the latest version as of this writing, and targeting .NET 6, for the record.
I see from Microsoft documentation that I can construct a DBContext to take a declared connection string, and a boolean indicating whether "[the] connection will be disposed when the context is disposed". This sounds like what I want, so I have altered the constructor for my DBContext from this:
public GenericAppContext()
{
}
public GenericAppContext(DbContextOptions<GenericAppContext> options)
: base(options)
{
}
to this:
public GenericAppContext(string connectionStringName, bool ownsConnection)
{
DbConnection conn = //declare the connection based on the given connection string name, somehow
}
I also have a Generic App Repository, which will use this context for its database calls. Currently, the repo is instantiating the context in the usual, default way:
private readonly GenericAppContext _context;
public GenericAppRepository(GenericAppContext context)
{
_context = context;
}
My actual connection strings are all declared in my appsettings.json file. Where I'm stuck is how to declare my generic context in my program.cs file, since obviously this isn't going to work...
builder.Services.AddDbContext<GenericAppContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("GeneralDataConnection")));
...because it declares an explicit connection. Do I even need to do this under these circumstances?
And then, how do I build my DbConnection from the given connection string name?