How to change database name in dbcontext connection string at runtime

后端 未结 3 2199
孤独总比滥情好
孤独总比滥情好 2020-12-06 23:34

My Asp.Net MVC application is setup as follows. There are 4 projects in solution.

  • ge.Web
  • ge.BLL
  • ge.Core
  • ge.Entities

<

相关标签:
3条回答
  • 2020-12-06 23:54

    You have two ways

    1)

        using System.Data.SqlClient;
    
             public class Repository<TEntity> : IRepository<TEntity> where TEntity:class
            {
                protected readonly GEContext context;
    
    
                public Repository(string connString, string schoolCode) {
                    context = new GEContext(connString);
                    var connection = new SqlConnectionStringBuilder(context.Database.Connection.ConnectionString);
                    connection.InitialCatalog = "YOUR_PREFIX_FROMSOMEWHERE"+schoolCode;
                    context.Database.Connection.ConnectionString = connection.ConnectionString;
                }
             }
    

    2) if you wants to switch connection when it opened before use ChangeDatabase:

    //open connection if it close
        context.Database.Connection.ChangeDatabase("DATABASE-NAME");
    

    NOTE: if use ChangeDatabase connection should be already opened

    FOR UPDATE3:

    You need to do somethink like this:

     public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
        {
            public ApplicationDbContext()
                : base("DefaultConnection", throwIfV1Schema: false)
            {
    
            }
    
            public ApplicationDbContext(string schoolCode)
                : base(schoolCode)
            {
                var connection = new SqlConnectionStringBuilder(this.Database.Connection.ConnectionString);
                connection.InitialCatalog = "YOUR_PREFIX_FROMSOMEWHERE" + schoolCode;
                this.Database.Connection.ConnectionString = connection.ConnectionString;
            }
    
            public static ApplicationDbContext Create()
            {
                return new ApplicationDbContext();
            }
        }
    

    in account controller:

    public ApplicationSignInManager SignInManager
            {
                get
                {
    
                    if (_signInManager == null)
                    {
                        var code = HttpContext.Request.Form.Get("SchoolCode");//Get from FORM\QueryString\Session whatever you wants
                        if (code != null)
                        {
                            HttpContext.GetOwinContext().Set<ApplicationSignInManager>(new ApplicationSignInManager(_userManager, HttpContext.GetOwinContext().Authentication));
                        }
                        _signInManager = HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
                    }
    
                    return _signInManager;
                }
                private set
                {
                    _signInManager = value;
                }
            }
    
     public ApplicationUserManager UserManager
            {
                get
                {
                    if (_userManager == null)
                    {
                        var code = HttpContext.Request.Form.Get("SchoolCode");//Get from FORM\QueryString\Session whatever you wants
                        if (code != null)
                        {
                            var appDbContext = new ApplicationDbContext(code);
    
                            HttpContext.GetOwinContext().Set<ApplicationDbContext>(appDbContext);
                            HttpContext.GetOwinContext().Set<ApplicationUserManager>(new ApplicationUserManager(new UserStore<ApplicationUser>(appDbContext))); //OR USE your specified create Method
                        }
                        _userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
                    }
                    return _userManager;
                }
                private set
                {
                    _userManager = value;
                }
            }
    

    Your problem is in Store of UserManager is created before you change your OWIN context, in this case better to use DI like here

    0 讨论(0)
  • 2020-12-07 00:07

    You can change the database for an open connection

    context.Database.GetDbConnection().ChangeDatabase("");
    
    0 讨论(0)
  • 2020-12-07 00:12

    I resolved it with the help of itikhomi..Posting the final code..

    ApplicationDbContext

    public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext("name=GEContext");
        }
    

    AccountController

     public ApplicationUserManager UserManager {
            get
            {
                if (System.Web.HttpContext.Current.Session["SchoolCode"] == null)
                    return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
                else
                {
                    var appDbContext = ApplicationDbContext.Create(System.Web.HttpContext.Current.Session["SchoolCode"].ToString());//new ApplicationDbContext("name=GEContext", System.Web.HttpContext.Current.Session["SchoolCode"].ToString());
    
                    HttpContext.GetOwinContext().Set<ApplicationDbContext>(appDbContext);
                    HttpContext.GetOwinContext().Set<ApplicationUserManager>(new ApplicationUserManager(new UserStore<ApplicationUser, Role, int, UserLogin, UserRole, UserClaim>(appDbContext)));
    
                    return HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
                }
            }
            private set
            {
                _userManager = value;
            }
        }
    
    0 讨论(0)
提交回复
热议问题