An ASP.NET Core MVC application uses virtual directory and cookie specific connection strings:
- http://example.com/database1
- Cookie value 1
- should use connection string:
Database=db1;Search_Path=company1
- should use connection string:
- Cookie value 2
- should use connection string:
Database=db1;Search_Path=company2
- should use connection string:
- Cookie value 1
- http://example.com/database2
- Cookie value 1
- should use connection string:
Database=db2;Search_Path=company1
- should use connection string:
- Cookie value 1
This Entity Framework Core tutorial contains sample code for setting connection string for an entire application:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SchoolContext")));
}
How to use request specific connection strings?
Update
I tried code in answer and added the following code to Home controller:
public class HomeController
{
public ActionResult Index()
{
using (var context = new SchoolContext(new DbContextOptions<SchoolContext>()))
{
var commandText = "INSERT into maksetin(maksetin) VALUES (1)";
context.Database.ExecuteSqlRaw(commandText);
}
This throws error
System.InvalidOperationException: 'No database provider has been configured for
this DbContext.
A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by
using 'AddDbContext' on the application service provider.
If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in
its constructor and passes it to the base constructor for DbContext.'
Breakpoint in line
IHttpContextAccessor http = sp.GetRequiredService<IHttpContextAccessor>();
does not occur. So code in answer is not called. How to force it call ?