Using entity framework on multiple databases

后端 未结 2 1510
悲&欢浪女
悲&欢浪女 2020-12-01 04:23

I am writing a payroll system that will integrate with a pre-existing system. The original system had a master database that handled user management and some global configur

相关标签:
2条回答
  • 2020-12-01 05:01

    EF6 has better support for multiple DB access from Same context. Here is a snippet from EF5. Managing the database initializer setting prior is important. You may not want to trigger ANY migrations. i.e, use this before

    Database.SetInitializer(new ContextInitializerNone<MyDbContext>());

    but to answer the question: Yes you can

    var conn = GetSqlConn4DbName(dataSource,dbName );
    var ctx = new MyDbContext(conn,true);
    
    
    
    public DbConnection GetSqlConn4DbName(string dataSource, string dbName) {
            var sqlConnStringBuilder = new SqlConnectionStringBuilder();
            sqlConnStringBuilder.DataSource = String.IsNullOrEmpty(dataSource) ? DefaultDataSource : dataSource;
            sqlConnStringBuilder.IntegratedSecurity = true;
            sqlConnStringBuilder.MultipleActiveResultSets = true;
    
            var sqlConnFact = new SqlConnectionFactory(sqlConnStringBuilder.ConnectionString);
            var sqlConn = sqlConnFact.CreateConnection(dbName);
            return sqlConn;
        }
    
    
     public class ContextInitializerNone<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext
    {
        public void InitializeDatabase(TContext context) {  }
    }
    

    Also see StackOverflow answer using migration, sample code, and dynamic db connection

    0 讨论(0)
  • 2020-12-01 05:07

    It is very simple. I have:

    public WMSEntities() : base("name=WMSEntities") //WMSEntities is conection string name in     web.config also the name of Entitiframework
    {
    }
    

    already in autogenerated Model.Context.cs of edmx folder

    To connect to multiple database in runtime, I created another constructor that takes connection string as parameter like below in same file Model.Context.cs

    public WMSEntities(string connStringName)
        : base("name=" + connStringName)
    {
    }
    

    Now I added other connection string in Web.Config for example

    <add name="WMSEntities31" connectionString="data source=TESTDBSERVER_NAME;initial catalog=TESTDB;userid=TestUser;password=TestUserPW/>
    
    <add name="WMSEntities" connectionString="data source=TESTDBSERVER_NAME12;initial catalog=TESTDB12;userid=TestUser12;password=TestUserPW12/>
    

    Then, when connecting to database I call below method passing connetionString name as parameter

    public static List<v_POVendor> GetPOVendorList(string connectionStringName)
    {
        using (WMSEntities db = new WMSEntities(connectionStringName))
        {               
            vendorList = db.v_POVendor.ToList();                 
        }
    }
    
    0 讨论(0)
提交回复
热议问题