Set Entity Framework Connection String at Runtime in C#

前端 未结 4 2050
孤街浪徒
孤街浪徒 2020-12-29 05:59

I need to set my Entity Framework connection string at runtime. Right now, I have the following:

string connectionString = \"metadata=res://*/DataModels.Cust         


        
相关标签:
4条回答
  • 2020-12-29 06:25

    It is easier to use EntityConnectionStringBuilder and SqlConnectionStringBuilder to change parameters as you want.

    0 讨论(0)
  • 2020-12-29 06:31

    Change this.

    string connectionString = "metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework"";
    

    To this (note how i escaped the " character as "" )

    string connectionString = @"metadata=res://*/DataModels.CustomerDataModel.csdl|res://*/DataModels.CustomerDataModel.ssdl|res://*/DataModels.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string= ""data source=tcp:{serverName},{portNumber};initial catalog={databaseName};user id={username};multipleactiveresultsets=True;application name=EntityFramework""";
    
    0 讨论(0)
  • 2020-12-29 06:35

    set multiple connection strings in your web.config, and follow below:

    public partial class MyDatabaseEntities
    {
        public MyDatabaseEntities(string connection)
            : base(connection)
        {
        }
    }
    

    and then wherever you want to create instance of entities, pass connection string name in parameter:

    MyDatabaseEntities entities = new MyDatabaseEntities("CONNECTION_STRING_NAME");
    

    I hope this will help.

    Thanks

    0 讨论(0)
  • 2020-12-29 06:36

    I know this was asked 10 months ago, but I found an easier way to specify the connectionString:

    If your config file has it as:

    <connectionStrings>
    <add name="CustomerDataModel" connectionString="metadata=res://*/EntityFramework.CustomerDataModel.csdl|res://*/EntityFramework.CustomerDataModel.ssdl|res://*/EntityFramework.CustomerDataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\CustomerDataModel;initial catalog=CustomerDB;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    

    You can specify it as -

    public const string ConnectionString = @"name=CustomerDataModel";
    ..
    CustomerDBContext context = new CustomerDBContext(ConnectionString );
    

    No need to worry about quotes. Lot cleaner.

    0 讨论(0)
提交回复
热议问题