ASP.NET Core change EF connection string when user logs in

28,803

Solution 1

It's been a long time since I posted this question, and I never shared the solution I developed, so I figured I should.

I ended up going the route of using different subdomains for my tenants. Because of this, I simply created a TenantService that checked the url and returned a connection string from config. Inside my DbContext's OnConfiguring method, I simply called the tenant service and used the returned connection string. Here is some sample code:

Tenant Service

public class Tenant
{
    public string Name { get; set; }

    public string Hostname { get; set; }

    public string ConnectionString { get; set; }
}

public interface ITenantService
{
    Tenant GetCurrentTenant();

    List<Tenant> GetTenantList();
}

public class TenantService : ITenantService
{
    private readonly ILogger<TenantService> _logger;
    private readonly IHttpContextAccessor _httpContext;
    private readonly IConfiguration _configuration;

    public TenantService(
        ILogger<TenantService> logger,
        IHttpContextAccessor httpContext,
        IConfiguration configuration)
    {
        _logger = logger;
        _httpContext = httpContext;
        _configuration = configuration;
    }

    /// <summary>
    /// Gets the current tenant from the host.
    /// </summary>
    /// <returns>The tenant.</returns>
    public Tenant GetCurrentTenant()
    {
        Tenant tenant;
        var host = _httpContext.HttpContext.Request.Host;
        var tenants = GetTenantList();

        tenant = tenants.SingleOrDefault(t => t.Hostname == host.Value);
        if (tenant == null)
        {
            _logger.LogCritical("Could not find tenant from host: {host}", host);
            throw new ArgumentException($"Could not find tenant from host: {host}");
        }
        return tenant;
    }

    /// <summary>
    /// Gets a list of tenants in configuration.
    /// </summary>
    /// <returns>The list of tenants.</returns>
    public List<Tenant> GetTenantList()
    {
        var tenants = new List<Tenant>();

        _configuration.GetSection("Tenants").Bind(tenants);

        return tenants;
    }
}

DbContext

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    base.OnConfiguring(optionsBuilder);

    if (!optionsBuilder.IsConfigured)
    {
        if (_tenantService == null)
        {
            throw new ArgumentNullException(nameof(_tenantService));
        }
        optionsBuilder.UseSqlServer(_tenantService.GetCurrentTenant().ConnectionString);
    }
}

Solution 2

Create a DbContext factory

public static class DbContextFactory
{
    public static Dictionary<string, string> ConnectionStrings { get; set; }

    public static void SetConnectionString(Dictionary<string, string> connStrs)
    {
        ConnectionStrings = connStrs;
    }

    public static MyDbContext Create(string connid)
    {
        if (!string.IsNullOrEmpty(connid))
        {
            var connStr = ConnectionStrings[connid];
            var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
            optionsBuilder.UseSqlServer(connStr);
            return new MyDbContext(optionsBuilder.Options);
        }
        else
        {
            throw new ArgumentNullException("ConnectionId");
        }
    }
}

Intialize DbContext factory

In startup.cs

public void Configure()
{
  Dictionary<string, string> connStrs = new Dictionary<string, string>();
  connStrs.Add("DB1", Configuration["Data:DB1Connection:ConnectionString"]);
  connStrs.Add("DB2", Configuration["Data:DB2Connection:ConnectionString"]);
  DbContextFactory.SetConnectionString(connStrs);
}

Usage

var dbContext= DbContextFactory.Create("DB1");

Solution 3

According to your question, I going to provide a solution assuming some things:

First, I've created three databases in my local SQL Server instance:

create database CompanyFoo
go

create database CompanyBar
go

create database CompanyZaz
go

Then, I going to create one table with one row in each database:

use CompanyFoo
go

drop table ConfigurationValue
go

create table ConfigurationValue
(
    Id int not null identity(1, 1),
    Name varchar(255) not null,
    [Desc] varchar(max) not null
)
go

insert into ConfigurationValue values ('Company name', 'Foo Company')
go

use CompanyBar
go

drop table ConfigurationValue
go

create table ConfigurationValue
(
    Id int not null identity(1, 1),
    Name varchar(255) not null,
    [Desc] varchar(max) not null
)
go

insert into ConfigurationValue values ('Company name', 'Bar Company')
go

use CompanyZaz
go

drop table ConfigurationValue
go

create table ConfigurationValue
(
    Id int not null identity(1, 1),
    Name varchar(255) not null,
    [Desc] varchar(max) not null
)
go

insert into ConfigurationValue values ('Company name', 'Zaz Company')
go

Next step is create an user with SQL Authentication and grant access to read the databases, in my case my user name is johnd and password is 123.

Once we have these steps completed, we proceed to create an MVC application in ASP.NET Core, I used MultipleCompany as project name, I have two controllers: Home and Administration, the goal is to show a login view first and then redirect to another view to show data according to selected database in "login" view.

To accomplish your requirement, you'll need to use session on ASP.NET Core application you can change this way to storage and read data later, for now this is for concept test only.

HomeController code:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MultipleCompany.Models;

namespace MultipleCompany.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(LoginModel model)
        {
            HttpContext.Session.SetString("CompanyCode", model.CompanyCode);
            HttpContext.Session.SetString("UserName", model.UserName);
            HttpContext.Session.SetString("Password", model.Password);

            return RedirectToAction("Index", "Administration");
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}

AdministrationController code:

using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using MultipleCompany.Models;
using MultipleCompany.Services;

namespace MultipleCompany.Controllers
{
    public class AdministrationController : Controller
    {
        protected IDbContextService DbContextService;
        protected CompanyDbContext DbContext;

        public AdministrationController(IDbContextService dbContextService)
        {
            DbContextService = dbContextService;
        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            DbContext = DbContextService.CreateCompanyDbContext(HttpContext.Session.CreateLoginModelFromSession());

            base.OnActionExecuting(context);
        }

        public IActionResult Index()
        {
            var model = DbContext.ConfigurationValue.ToList();

            return View(model);
        }
    }
}

Code for Home view:

@{
    ViewData["Title"] = "Home Page";
}

<form action="/home" method="post">
    <fieldset>
        <legend>Log in</legend>

        <div>
            <label for="CompanyCode">Company code</label>
            <select name="CompanyCode">
                <option value="CompanyFoo">Foo</option>
                <option value="CompanyBar">Bar</option>
                <option value="CompanyZaz">Zaz</option>
            </select>
        </div>

        <div>
            <label for="UserName">User name</label>
            <input type="text" name="UserName" />
        </div>

        <div>
            <label for="Password">Password</label>
            <input type="password" name="Password" />
        </div>

        <button type="submit">Log in</button>
    </fieldset>
</form>

Code for Administration view:

@{
    ViewData["Title"] = "Home Page";
}

<h1>Welcome!</h1>

<table class="table">
    <tr>
        <th>Name</th>
        <th>Desc</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.Desc</td>
        </tr>
    }
</table>

LoginModel code:

using System;
using Microsoft.AspNetCore.Http;

namespace MultipleCompany.Models
{
    public class LoginModel
    {
        public String CompanyCode { get; set; }

        public String UserName { get; set; }

        public String Password { get; set; }
    }

    public static class LoginModelExtensions
    {
        public static LoginModel CreateLoginModelFromSession(this ISession session)
        {
            var companyCode = session.GetString("CompanyCode");
            var userName = session.GetString("UserName");
            var password = session.GetString("Password");

            return new LoginModel
            {
                CompanyCode = companyCode,
                UserName = userName,
                Password = password
            };
        }
    }
}

CompanyDbContext code:

using System;
using Microsoft.EntityFrameworkCore;

namespace MultipleCompany.Models
{
    public class CompanyDbContext : Microsoft.EntityFrameworkCore.DbContext
    {
        public CompanyDbContext(String connectionString)
        {
            ConnectionString = connectionString;
        }

        public String ConnectionString { get; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(ConnectionString);

            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

        public DbSet<ConfigurationValue> ConfigurationValue { get; set; }
    }
}

ConfigurationValue code:

using System;

namespace MultipleCompany.Models
{
    public class ConfigurationValue
    {
        public Int32? Id { get; set; }

        public String Name { get; set; }

        public String Desc { get; set; }
    }
}

AppSettings code:

using System;

namespace MultipleCompany.Models
{
    public class AppSettings
    {
        public String CompanyConnectionString { get; set; }
    }
}

IDbContextService code:

using MultipleCompany.Models;

namespace MultipleCompany.Services
{
    public interface IDbContextService
    {
        CompanyDbContext CreateCompanyDbContext(LoginModel model);
    }
}

DbContextService code:

using System;
using Microsoft.Extensions.Options;
using MultipleCompany.Models;

namespace MultipleCompany.Services
{
    public class DbContextService : IDbContextService
    {
        public DbContextService(IOptions<AppSettings> appSettings)
        {
            ConnectionString = appSettings.Value.CompanyConnectionString;
        }

        public String ConnectionString { get; }

        public CompanyDbContext CreateCompanyDbContext(LoginModel model)
        {
            var connectionString = ConnectionString.Replace("{database}", model.CompanyCode).Replace("{user id}", model.UserName).Replace("{password}", model.Password);

            var dbContext = new CompanyDbContext(connectionString);

            return dbContext;
        }
    }
}

Startup code:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MultipleCompany.Models;
using MultipleCompany.Services;

namespace MultipleCompany
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddEntityFrameworkSqlServer().AddDbContext<CompanyDbContext>();

            services.AddScoped<IDbContextService, DbContextService>();

            services.AddDistributedMemoryCache();
            services.AddSession();

            services.AddOptions();

            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            services.AddSingleton<IConfiguration>(Configuration);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

I've added this packages for my project:

"Microsoft.EntityFrameworkCore": "1.0.1",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.AspNetCore.Session":  "1.0.0"

My appsettings.json file:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "AppSettings": {
    "CompanyConnectionString": "server=(local);database={database};user id={user id};password={password}"
  }
}

Please get focus on the concept about to connect to selected database in home view, you can change any part of this code as an improvement, please remember I'm providing this solution making some assumptions according to your brief question, please feel free to ask about any exposed aspect in this solution to improve this piece of code according to your requirements.

Basically, we need to define a service to create the instance of db context according to selected database, that's IDbContextService interface and DbContextService it's the implementation for that interface.

As you can see on DbContextService code, we replace the values inside of {} to build different connection string, in this case I've added the database names in drop down list but in real development please avoid this way because for security reasons it's better to don't expose the real names of your databases and other configurations; you can have a parity table from controller's side to resolve the company code according to selected database.

One improvement for this solution, it would be to add some code to serialize login model as json into session instead of store each value in separate way.

Please let me know if this answer is useful. PD: Let me know in comments if you want the full code to upload in one drive

Solution 4

You found your answer but maybe my post can be helpful for someones. I had a similar problem like this question. I have had to change my entity framework connectionstring to connect different database server after user logged in. And for solution first I deleted this function from my context class,

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer("your connectionstring...");
            }

because I couldn't called this function from outside. And I had this auto generated constructor

 public ClientContext(DbContextOptions<ClientContext> options)
        : base(options)
    {
    }

After deletion, I added this code to my context class.

public ClientContext CreateConnectionFromOut(string connectionString)
{
    var optionsBuilder = new DbContextOptionsBuilder<Esdesk_ClientContext>();
    optionsBuilder.UseSqlServer(connectionString);
    var context = new ClientContext(optionsBuilder.Options);
    return context;
}

Now finally, I can change my connection string from wherever I want. It is just like that,

   ClientContext cc = new ClientContext();
   var db = cc.CreateConnectionFromOut("your connection string");

Hope this may be fine for someone.

Solution 5

Since you are building a multi-tenant web application, you have to first decide how will you distinguish between tenants. Are you going to use differnent URL? or maybe the same URL but adding a part in the URL?

Assuming that you chose the latter, so tenant 1 would have a URL similar to this: http://localhost:9090/tenant1/orders

Tenant 2 would have a URL like: http://localhost:9090/tenant2/orders

You can do that using URL routing:

 routes.MapRoute(
                name: "Multitenant",
                url: "{tenant}/{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

As for the connection string, you need a class to decide the connection string based on the URL, and inject this class into the DB context.

public interface ITenantIdentifier
{
 string GetCurrentTenantId();
}

public class UrlTenantIdentifier : ITenantIdentifier
{
  public string GetCurrentTenantId()
  { 
    //Get the current Http Context and get the URL, you should have a table or configration that maps the URL to the tenant ID and connection string
  }
}

In your DB Context:

public class MyDbContext: DbContext
{
 public MyDbContext(ITenantIdentifier tenantIdentifier)
 { 
   var connectionStringName = "TenantConnectionString"+tenantIdentifier.GetCurrentTenantId(); //here assuming that you are following a pattern, each tenant has a connection string in the shape of TenantConnectionString+ID

  var connectionString = //get connection string
  base(connectionString);
 }
}
Share:
28,803
Alex
Author by

Alex

Updated on July 09, 2022

Comments

  • Alex
    Alex almost 2 years

    After a few hours of research and finding no way to do this; it's time to ask the question.

    I have an ASP.NET Core 1.1 project using EF Core and MVC that is used by multiple customers. Each customer has their own database with the exact same schema. This project is currently a Windows application being migrated to the web. At the login screen the user has three fields, Company Code, Username and Password. I need to be able to change the connection string when the user attempts to login based on what they type in the Company Code input then remember their input throughout the session duration.

    I found some ways to do this with one database and multiple schema, but none with multiple databases using the same schema.

    The way I solved this problem isn't an actual solution to the problem, but a work around that worked for me. My databases and app are hosted on Azure. My fix to this was to upgrade my app service to a plan that supports slots (only an extra $20 a month for 5 slots). Each slot has the same program but the environment variable that holds the connection string is company specific. This way I can also subdomain each companies access if I want. While this approach may not be what others would do, it was the most cost effective to me. It is easier to publish to each slot than to spend the hours doing the other programming that doesn't work right. Until Microsoft makes it easy to change the connection string this is my solution.

    In response to Herzl's answer

    This seems like it could work. I have tried to get it implemented. One thing I am doing though is using a repository class that accesses my context. My controllers get the repository injected into them to call methods in the repository that access the context. How do I do this in a repository class. There is no OnActionExecuting overload in my repository. Also, if this persists for the session, what happens when a user opens their browser to the app again and is still logged in with a cookie that lasts 7 days? Isn't this a new session? Sounds like the app would throw an exception because the session variable would be null and therefor not have a complete connection string. I guess I could also store it as a Claim and use the Claim if the session variable is null.

    Here is my repository class. IDbContextService was ProgramContext but I started adding your suggestions to try and get it to work.

    public class ProjectRepository : IProjectRepository
    {
        private IDbContextService _context;
        private ILogger<ProjectRepository> _logger;
        private UserManager<ApplicationUser> _userManager;
    
        public ProjectRepository(IDbContextService context,
                                ILogger<ProjectRepository> logger,
                                UserManager<ApplicationUser> userManger)
        {
            _context = context;
            _logger = logger;
            _userManager = userManger;
        }
    
        public async Task<bool> SaveChangesAsync()
        {
            return (await _context.SaveChangesAsync()) > 0;
        }
    }
    

    In response to The FORCE JB's answer

    I tried to implement your approach. I get an exception in Program.cs on line

    host.Run();
    

    Here is my 'Program.cs' class. Untouched.

    using System.IO;
    using Microsoft.AspNetCore.Hosting;
    
    namespace Project
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                var host = new WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .Build();
    
                host.Run();
            }
        }
    }
    

    And my 'Startup.cs' class.

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json.Serialization;
    using System;
    using System.Collections.Generic;
    using Project.Entities;
    using Project.Services;
    
    namespace Project
    {
        public class Startup
        {
            private IConfigurationRoot _config;
    
            public Startup(IHostingEnvironment env)
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json")
                    .AddEnvironmentVariables();
    
                _config = builder.Build();
            }
    
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddSingleton(_config);
                services.AddIdentity<ApplicationUser, IdentityRole>(config =>
                {
                    config.User.RequireUniqueEmail = true;
                    config.Password.RequireDigit = true;
                    config.Password.RequireLowercase = true;
                    config.Password.RequireUppercase = true;
                    config.Password.RequireNonAlphanumeric = false;
                    config.Password.RequiredLength = 8;
                    config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
                    config.Cookies.ApplicationCookie.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0); // Cookies last 7 days
                })
                .AddEntityFrameworkStores<ProjectContext>();
                services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();
                services.AddScoped<IProjectRepository, ProjectRepository>();
                services.AddTransient<MiscService>();
                services.AddLogging();
                services.AddMvc()
                .AddJsonOptions(config =>
                {
                    config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                });
            }
    
            public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
            {
                Dictionary<string, string> connStrs = new Dictionary<string, string>();
                connStrs.Add("company1", "1stconnectionstring"));
                connStrs.Add("company2", "2ndconnectionstring";
                DbContextFactory.SetDConnectionString(connStrs);
                //app.UseDefaultFiles();
    
                app.UseStaticFiles();
                app.UseIdentity();
                app.UseMvc(config =>
                {
                    config.MapRoute(
                        name: "Default",
                        template: "{controller}/{action}/{id?}",
                        defaults: new { controller = "Auth", action = "Login" }
                        );
                });
            }
        }
    }
    

    And the exception:

    InvalidOperationException: Unable to resolve service for type 'Project.Entities.ProjectContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4[Project.Entities.ApplicationUser,Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole,Project.Entities.ProjectContext,System.String]'.
    

    Not sure what to do here.

    Partial success edit

    Okay I got your example working. I can set the connection string in my repository constructor using a different id. My problem now is logging in and choosing the right database. I thought about having the repository pull from a session or claim, whatever wasn't null. But I can't set the value before using the SignInManager in the Login controller because SignInManager is injected into the controller which creates a context before I update the session variable. The only way I can think of is to have a two page login. The first page will ask for the company code and update the session variable. The second page will use the SignInManager and have the repository injected into the controllers constructor. This would happen after the first page updates the session variable. This may actually be more visually appealing with animations between both login views. Unless anyone has any ideas on a way to do this without two login views I am going to try and implement the two page login and post the code if it works.

    It is actually broken

    When it was working, it is because I still had a valid cookie. I would run the project and it would skip the login. Now I get the exception InvalidOperationException: No database provider has been configured for this DbContext after clearing my cache. I have stepped through it all and the context is being created correctly. My guess is that Identity is having some sort of issues. Could the below code adding the entity framework stores in ConfigureServices be causing the issue?

    services.AddIdentity<ApplicationUser, IdentityRole>(config =>
    {
        config.User.RequireUniqueEmail = true;
        config.Password.RequireDigit = true;
        config.Password.RequireLowercase = true;
        config.Password.RequireUppercase = true;
        config.Password.RequireNonAlphanumeric = false;
        config.Password.RequiredLength = 8;
        config.Cookies.ApplicationCookie.LoginPath = "/Company/Login";
        config.Cookies.ApplicationCookie.ExpireTimeSpan = new TimeSpan(7, 0, 0, 0); // Cookies last 7 days
    })
    .AddEntityFrameworkStores<ProgramContext>();
    

    Edit

    I verified Identity is the problem. I pulled data from my repository before executing PasswordSignInAsync and it pulled the data just fine. How is the DbContext created for Identity?

  • Alex
    Alex over 7 years
    Creating another database for the users isn't an option for me. I would have to pay for another database and do a bunch of data transfer. There has to be a way to code this so I don't have to do that. I have looked at the connection string builder. If I was to use this how would I inject the connection string into the DbContext OnConfiguring method so it uses the database I want during queries?
  • Alex
    Alex over 7 years
    I have tried that from other posts. The Connection property in Database was removed in EF Core. If I could do this, do you know how I would pass a string to the parameter connString when an instance of the Context is instantiated?
  • CodingYoshi
    CodingYoshi over 7 years
    You pass it to the constructor. I just did this a few days ago and it works. You pass it before it is instantiated (in the constructor). I edited my post. You dont need to do nothing except for create a partial with single parameter constructor.
  • Alex
    Alex over 7 years
    How do I use this when my DbContext is injected into the class that uses it with dependency injection?
  • KarateJB
    KarateJB over 7 years
    Refer to http://stackoverflow.com/a/32210383/7045253, using the injection container would not allow you to change the default connection. Also see this related article, http://stackoverflow.com/a/36840901/7045253
  • Alex
    Alex over 7 years
    Please see the addition to my question.
  • KarateJB
    KarateJB over 7 years
    Hi, @ozziwald, "Unable to resolve service" may occurs while you use the injection service which was not initialized. In this case, if you still want to inject EF service to the controllers, add services.AddDbContext<DefaultDbContext>(...) for a default connection on startup.cs. And if you would like to change the connection, turns to use DbContextFactory to create new connection for other database. Hope this helps.
  • Alex
    Alex over 7 years
    services.AddDbContext<DbContextFactory>(); does not compile because DbContextFactory is static.
  • KarateJB
    KarateJB over 7 years
    DbContextFactory is used for creating new dbcontext object. While a user login, use 'var dbContext= DbContextFactory.Create("xxx")' to create a new dbcontext with mapping connecting string for this user.
  • Alex
    Alex over 7 years
    Okay so use AddDbContext like normal and use the factory to change the connection on the fly. I thought I tried that but I will give it another go and let you know what happens.
  • KarateJB
    KarateJB over 7 years
    Hi, @ozziwald. Yes, that's correct. I had my project runs like this for connecting to different database and its fine with ms sql server.
  • Alex
    Alex over 7 years
    With the two page login screen? Or just your example for changing the connection?
  • KarateJB
    KarateJB over 7 years
    I get data from different database, not depends on the login user. But what "With the two page login screen" means? I thought that each customer owns his/her own database, and all we do is changing the db connection.
  • Alex
    Alex over 7 years
    If I pass the login view model to the controller to change the database to whatever is in the CompanyCode before signing in, the signInManager has already created a DbContext when it was injected into the constructor, with the default string, not with the correct string. So I have to set the company code in a different controller/view then go to the actual login view that does the signing in.
  • KarateJB
    KarateJB over 7 years
    I think that validating user should with a default master database. After login, change to the mapping database. And maybe using linked server & store procedure will decrease the complexity.
  • Alex
    Alex over 7 years
    There should be a way to override the DbContext that Identity creates just like your suggestion for the first part of the problem. Maybe I should make a new question for this.
  • Alex
    Alex over 7 years
    This is the answer to part of the question.
  • user1447718
    user1447718 almost 7 years
    @TheFORCEJB - how do i use the variable dbContext in the startup.cs file?
  • KarateJB
    KarateJB almost 7 years
    @user1447718, you can use var dbContext = DbContextFactory.Create("Conn1"); after DbContextFactory.SetConnectionString(...)
  • user1447718
    user1447718 almost 7 years
    @TheFORCEJB but how to i add it using AddDBContext?
  • Alexandra Damaschin
    Alexandra Damaschin almost 6 years
    I tried to follow you because it makes sense to me, but I got an error: , error: 40 - Could not open a connection to SQL Server...how did you created the users?
  • H. Herzl
    H. Herzl almost 6 years
    According to your error message, you need to review your connection string
  • Alexandra Damaschin
    Alexandra Damaschin almost 6 years
    The same connection string I try it in another app and it worked
  • Brett Rigby
    Brett Rigby over 4 years
    EntityConnectionStringBuilder isn't supported by EF Core. :-(