简体   繁体   中英

How to Change the ConnectionString in Entity Framework 5 on Application Start

I'm using EF5 database-first with test and prod database servers (identical schemas) on an ASP.NET Web Forms app (4.5). Is there a way to dynamically set the target connection string in Application_Start of global.asax? So when I'm on the test server use the "test" connection string and when I'm on the prod server use the "prod" connection string.

Did you take a look at http://msdn.microsoft.com/en-us/library/gg679467%28v=vs.103%29.aspx DbContext(string connection)?

ObjectContext: http://msdn.microsoft.com/en-us/library/bb739017.aspx

Keep in mind that the connection string of ObjectContext is not a classic connection string but a EF connection string which is more complicated.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="Database1Entities" 
         connectionString="metadata=res://*/Model1.csdl
|res://*/Model1.ssdl
|res://*/Model1.msl;
provider=System.Data.SqlClient;provider connection string="
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;
Integrated Security=True;
User Instance=True;
MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

See also http://msdn.microsoft.com/en-us/library/system.data.entityclient.entityconnection.aspx . With entity-connection, you can create a ObjectContext based on a anready existing classical DbConnection.

希望这有助于其他人 - 但看起来我们将能够通过以下示例找到一种方法: https//stackoverflow.com/a/8240733/448704

For these kind of tasks I would suggest using built in to VS tools. Using them Visual Studio will automatically switch configuration (not only connection string) based on server you want to publish. Check out this link for more info: Web Deployment Made Awesome

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM