none
CORE2 Changing Connection String from DBContext DI at runtime RRS feed

  • Question

  • I need to change the Connection String from my ApplicationDataContext. Depending on the user who is authenticated  I need to point to a different database.

    What would be the code and where to changed it (AccountController/Login)?

    My function setContext() doesn't do anything when called from a controller.

    Using Core 2.0.

    startup.cs

    public void ConfigureServices(IServiceCollection services)
            {
                // Add our Config object so it can be injected
                services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
                
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
                services.AddDbContext<ApplicationDataContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("ConnectionToBeChanged")));
    }

    ApplicationDbContext.cs

    public class ApplicationDataContext:DbContext
        {
            public ApplicationDataContext(DbContextOptions<ApplicationDataContext> options)
                : base(options)
            {
            }
    
            protected override void OnModelCreating(ModelBuilder builder)
            {
                base.OnModelCreating(builder);
                
                builder.Entity<Organisation>()
                .HasOne(c => c.Parent);
            }
    }

    BaseController.cs

    public class BaseController : Controller
        {
            private readonly IOptions<AppSettings> appSettings;
            public ApplicationDataContext _context;
            private readonly UserManager<ApplicationUser> _userManager;
            private readonly IHttpContextAccessor _httpContextAccessor;
    
            public BaseController(IOptions<AppSettings> AppSettings, ApplicationDataContext Context, UserManager<ApplicationUser> userManager, IHttpContextAccessor httpContextAccessor)
            {
                appSettings = AppSettings;
                _userManager=userManager;
                _context = Context;
                _httpContextAccessor = httpContextAccessor;
                
                setContext();
            }
    
            public async void setContext()
            {
                if (!_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated )
                    return;
    
                var r = await _userManager.GetRolesAsync(await _userManager.GetUserAsync(_httpContextAccessor.HttpContext.User));
                if (ConstantVar.listOfClass.Keys.Contains(r.FirstOrDefault().ToUpper()))
                {
                    var con = ConstantVar.listOfClass[r.FirstOrDefault().ToUpper()];
                    var options = new DbContextOptionsBuilder<ApplicationDataContext>();
                    options.UseSqlServer(con);
                    _context = new ApplicationDataContext(options.Options);
                }
            }
        }
    Thanks a lot


    • Edited by hobie1 Wednesday, September 6, 2017 7:31 AM
    • Moved by CoolDadTx Wednesday, September 6, 2017 2:28 PM ASP.NET related
    Wednesday, September 6, 2017 7:28 AM

Answers

All replies

  • I need to change the Connection String from my ApplicationDataContext. Depending on the user who is authenticated  I need to point to a different database.

    What would be the code and where to changed it (AccountController/Login)?

    My function setContext() doesn't do anything when called from a controller

    Of course, ASP.NET Identity database  that the AccountController is using is working with the ADO.NET Entity Framework, right?

    This is also assuming that the DB you are trying to point to is another  ASP.NET Identity DB on a different server with the EF virtual model derived from an ASP.NET Identity DB.

    If that is the case where you are just pointing to another ASP.NET Identity DB on another server, then you can change the connectionstring programmically to point to another ASP.NET Identity DB that EF is using.

    If that is not the case, then you can't be using the connectionstring that is using EF that is pointing to an ASP.NET Identity DB.

    You will have to use a different connectionstring away from the one EF is using to point to another DB where EF is not being used, and the DB is on another server.

    ASP.NET MVC and Identity can be discussed at the ASP.NET forum.

    I could be wrong, but the connectionstring used by EF is tightly bound to EF functionality. 

    http://forums.asp.net/

    Wednesday, September 6, 2017 11:07 AM
  • Please post questions related to ASP.NET in the ASP.NET forums.
    Wednesday, September 6, 2017 2:28 PM
  • Fixed using the DBContextFactory Concept and DI.
    • Marked as answer by hobie1 Wednesday, September 6, 2017 8:14 PM
    Wednesday, September 6, 2017 8:14 PM