Entity Framework 6 set connection string runtime

后端 未结 3 711
日久生厌
日久生厌 2020-12-08 07:50

We are in a mixed environment where our application is using both ADO.NET and Entity Framework.
Since both are pointing to the same physical SQL server, we would like to

3条回答
  •  無奈伤痛
    2020-12-08 08:14

    You can work at design time using the connection string in your config file.

    
    

    So don't remove it because you need it ONLY at design time.

    Work instead in a dynamic way at runtime using this approach (similar to your last one):

    Extend the data context partial class:

    public partial class DWContext
    {
        public DWContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }
    
        /// 
        /// Create a new EF6 dynamic data context using the specified provider connection string.
        /// 
        /// Provider connection string to use. Usually a standart ADO.NET connection string.
        /// 
        public static DWContext Create(string providerConnectionString)
        {
            var entityBuilder = new EntityConnectionStringBuilder();
    
            // use your ADO.NET connection string
            entityBuilder.ProviderConnectionString = providerConnectionString;
    
            entityBuilder.Provider = "System.Data.SqlClient";
    
            // Set the Metadata location.
            entityBuilder.Metadata = @"res://*/Database.DWH.DWModel.csdl|res://*/Database.DWH.DWModel.ssdl|res://*/Database.DWH.DWModel.msl";
    
            return new DWContext(entityBuilder.ConnectionString);
        }
    
    }
    

    And from your code create a new EF data context with:

    private DWContext db = DWContext.Create(providerConnectionString);
    

    Ciao ;-)

提交回复
热议问题