Pass Connection String At Run Time to Entity Framework

A few days ago I was tasked to implement a Web API application to fetch and expose data using the Entity Framework, Cool!! It's the latest technology but there was a little tweak in that. The connection string to fetch the data from the database will come from another service.

Hmm, It was DB first approach application because our database was already built and we just needed to write code to process the data. We know that Entity Framework automatically generates a connection string at the time of model creation , if you closely look at the connection string you will find that there is a little more information within the connection string, the string is not a straight-forward connection string as we see generally for the ADO.NET environment.

Here is one example for your better understanding.

  1. <add name="efDBEntities"  
  2. connectionString="metadata=res://*/testModel.csdl|res://*/testModel.ssdl|res://*/testModel.msl;  
  3. provider=System.Data.SqlClient;  
  4. provider connection string="  
  5. data source=SOURAV-PC;initial catalog=efDB;  
  6. user id=sourav;password=password;  
  7. MultipleActiveResultSets=True;  
  8. App=EntityFramework""  
  9. providerName="System.Data.EntityClient" />
Just have a look at that metadata property and all the other stuff in there along with username, password, initialCatalog and data source name.

If you want to build your own connection string by setting all those properties at run time then here is the solution. Just open the context file of Entity Framework and modify the code as in the following. In this example we have implemented a Singleton class to supply the connection string. The reason is, when the first request hits a controller to fetch data, the connection string will be formed and it will be used by every subsequent request.
  1. namespace WebAPI  
  2. {  
  3.     using System;  
  4.     using System.Data.Entity;  
  5.     using System.Data.Entity.Core.EntityClient;  
  6.     using System.Data.Entity.Infrastructure;  
  7.     using System.Data.SqlClient;  
  8.     public class SingleConnection  
  9.     {  
  10.         private SingleConnection(){}  
  11.         private static SingleConnection _ConsString = null;  
  12.         private String _String = null;  
  13.         public static string ConString  
  14.         {  
  15.             get  
  16.             {  
  17.                 if (_ConsString == null)  
  18.                 {  
  19.                     _ConsString = new SingleConnection { _String = SingleConnection.Connect() };  
  20.                     return _ConsString._String;  
  21.                 }
  22.                 else  
  23.                   return _ConsString._String;  
  24.             }  
  25.         }  
  26.         public static string Connect()  
  27.         {  
  28.             //Build an SQL connection string  
  29.             SqlConnectionStringBuilder sqlString = new SqlConnectionStringBuilder()  
  30.             {  
  31.                 DataSource = "SOURAV-PC"// Server name  
  32.                 InitialCatalog = "efDB",  //Database  
  33.                 UserID = "sourav",         //Username  
  34.                 Password = "mypassword",  //Password  
  35.             };  
  36.             //Build an Entity Framework connection string  
  37.             EntityConnectionStringBuilder entityString = new EntityConnectionStringBuilder()  
  38.             {  
  39.                 Provider = "System.Data.SqlClient",  
  40.                     Metadata =   "res://*/testModel.csdl|res://*/testModel.ssdl|res://*/testModel.msl",  
  41.                 ProviderConnectionString = sqlString.ToString()  
  42.             };  
  43.             return entityString.ConnectionString;  
  44.         }  
  45.     }  
  46.     public partial class efDBEntities : DbContext  
  47.     {  
  48.         public efDBEntities() : base(SingleConnection.ConString)  
  49.         {  
  50.             //"name=efDBEntities"  
  51.         }  
  52.         protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  53.         {  
  54.             throw new UnintentionalCodeFirstException();  
  55.         }  
  56.     }  
  57. }  
In the example we have used the Connect() function to populate all the properties, if needed then the credentials can be pulled from another application.

Thanks, Happy learning.