Change Database during runtime in Entity Framework, without changing the Connection

前端 未结 6 1660
一生所求
一生所求 2020-12-14 01:59

I have a server that hosts 50 databases with identical schemas, and I want to start using Entity Framework in our next version.

I don\'t need a new connection for ea

6条回答
  •  臣服心动
    2020-12-14 02:46

    EntityConnection.ChangeDatabase method is not supported, but SqlConnection.ChangeDatabase works fine.

    So you have to use SqlConnection in entity framework database's constructor:

    using MvcMyDefaultDatabase.Models;
    using System.Data.Metadata.Edm;
    using System.Data.SqlClient;
    using System.Data.EntityClient;
    using System.Configuration;
    using System.Reflection;
    
        public ActionResult List(string Schema)
        {
            SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
    
            MetadataWorkspace workspace = new MetadataWorkspace(new string[] { "res://*/" }, new Assembly[] { Assembly.GetExecutingAssembly() });
    
            EntityConnection entityConnection = new EntityConnection(workspace, sqlConnection);
    
            sqlConnection.Open();
    
            sqlConnection.ChangeDatabase(Schema);
    
            Models.MyEntities db = new MyEntities(entityConnection);
    
            List MyTableRecordsList = db.MyTableRecords.ToList();
    
            return View(MyTableRecordsList);
        }
    

    With this code you can read the tables with the same format (same table name and same fields) of several schema passing the database name in the "Schema" string.

提交回复
热议问题