Single Connection String with Multiple Entity Framework Models?

后端 未结 3 2190
孤街浪徒
孤街浪徒 2021-02-08 18:33

At work we currently have a very large web application with a connection to a massive database. We have been using Entity Framework for a while now and to make things easier we

3条回答
  •  既然无缘
    2021-02-08 19:01

    This is how I have implemented my solution to this problem:

    namespace DBLibrary
    {
        public enum Models
        {
            Model1,
            Model2    
        }
    
        public static class Database
        {
            public static string EntitiesConnectionString(Models model)
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["Default"].ConnectionString);
    
                builder["MultipleActiveResultSets"] = true;
                builder["Connect Timeout"] = 30;
    
                EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
                entityBuilder.Provider = "System.Data.SqlClient";
                entityBuilder.ProviderConnectionString = builder.ConnectionString;
    
                switch (model)
                {
                    case Models.Model1:
                        entityBuilder.Metadata = "res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl";
                        return entityBuilder.ToString();
                    case Models.Model2:
                        entityBuilder.Metadata = "res://*/Model2.csdl|res://*/Model2.ssdl|res://*/Model2.msl";
                        return entityBuilder.ToString();
                    default:
                        throw new Exception("Invalid model, no connection string defined");
                }
            }
        }
    }
    

    I still need to clean up the code and all but I think this give you a good idea on how this can be implemented. I would still be very interested if there are different and better ways of doing this.

    Thanks!

提交回复
热议问题