Search code examples
asp.net-mvcentity-frameworkruntimeconnection-stringwindows-authentication

How to manage connection string in runtime with windows authentication


I'm developing an asp.net mvc web application using Entity Framework. The same application is supposed to be deployed in an intranet model for different clients.

My application is getting data from client databases who have exactly the same structure but with different data for each client, this is why i'm obliged to modify connection string in run-time to match the client environment (DB name and Server name). In addition to that my web app uses Windows Authentication to connect to database.

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

What I'd like to know is how is it possible to modify connection string in run-time knowing that the user have to type Server name and Database name once the application runs? And, how to integrate Windows Authentication to connect to the Database ?


Solution

  • So this question is in two parts. The comments so far answer the first part (dynamically pass connection string for DbContext at runtime).

    public TheDbContext() : base("the connection string goes here"){}
    

    For the second part, you may need to add <authentication mode="Windows"> in web.config. Also, in IIS enable Windows Authentication and disable Anonymous Authentication.