Thursday, March 31, 2011

How to specify connection string to SQL CE 4.0 for DbContext

Recently I've started playing with Entity Framework 4.1 RC.

I've faced a question on how to specify DbContext's connection string to SQL CE 4.0 at runtime. I managed to do it in app.config like this:



   
       
          name="MyContext"
          providerName="System.Data.SqlServerCe.4.0"
          connectionString="Data Source=C:\database.sdf;Encryption mode=platform default;password=123;" />
   


Assuming that my context is named MyContext.

But it appeared to be a difficult task if I don't want to store my connection string in config file. I wished to construct it on runtime to set a password. Passing Provider in connection string did not help.

The solution is to create Sql CE connection by the function from System.Data.SqlServerCe.dll (can be found in C:\Program Files\Microsoft SQL Server Compact Edition\v4.0\Desktop as follows:


            var connection = System.Data.SqlServerCe.SqlCeProviderFactory.Instance.CreateConnection();
            connection.ConnectionString = "Data Source=C:\database.sdf;Encryption mode=platform default;password=123;";


            
            var db = new MyContext(connection); // MyContext: DbContext




You also need to modify MyContext's constructor to pass connection to protected constructor of DbContext.