locked
Set dynamic dbcontext connection string after AspNetUser logs in RRS feed

  • Question

  • User-17504853 posted

    Is there some example about setting the dbcontext connection string after identity user logs in?
    I'm thinking about sending some user key when calling Login method and then setting some DI service property, for example ProgramConfig.ConnectionString....but how can I access it from the dbcontext constructor?

    Thanks!

    Monday, December 28, 2020 10:46 PM

All replies

  • User1312693872 posted

    Hi,bernardj1905

    Is there some example about setting the dbcontext connection string after identity user logs in?

    You can create a dbcontext factory and call different connection string according to the login user:

    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)     //judge which connectionstring to use by connid, from Configure()
        {
            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");
            }
        }
    }

    and in Configure(): 

    Dictionary<string, string> connStrs = new Dictionary<string, string>();
    connStrs.Add("DB1", "Server=***;Database=***;***;MultipleActiveResultSets=true");
    connStrs.Add("DB2", Your connection string);
    DbContextFactory.SetConnectionString(connStrs);

    then the way to use:

    if(user is login)
    {...
    var dbContext = DbContextFactory.Create("DB1"); var model = dbContext.Gate.ToList(); //......as usual
    }
    if(user is **)
    {
    ...
    var dbContext = DbContextFactory.Create("DB2");
    ...
    }

    Best Regards,

    Jerry Cai

    Tuesday, December 29, 2020 9:46 AM
  • User-17504853 posted

    Hi Jerry!

    Thanks for the answer, I'll try with your advice. Just, how can I use the factory in the dbcontext constructor?

    Thanks!
    Bernard.

    Tuesday, December 29, 2020 8:33 PM
  • User1312693872 posted

    Hi,bernardj1905

    You do not have to change the dbcontext constructor, this factory just offers a way to select which database too use. you can control which

    database connection string to use (or not) after identity user logs in.

    Best Regards,

    Jerry Cai

    Wednesday, December 30, 2020 6:23 AM