Dynamically alter EntityFramework ConnectionString in Domain Service
The Problem
One of the requirements for a Silverlight 4/WCF RIA Service application that I am working on is that the connection string is stored encrypted within the web.config file. This left me with the problem that I would need to somehow unencrypt the connection string and manually set it before any database interaction was done.
Fortunately there is a virtual method inside the LinqToEntitiesDomainService class that is created, overriding this allows you to set the connection string before the database is accessed.
The Code
The below code shows an example of overriding the CreateObjectContext() method.
In the code I fetch the encrypted connection string from the web.config file, decrypt it and then return a new EntitySet using this connection string.
using System.Configuration;
[EnableClientAccess()]
public class TestDomainService : LinqToEntitiesDomainService<TestEntities>
{
protected override TestEntities CreateObjectContext()
{
string encConnection = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
string decConnection = encConnection.Decrypt();
return new TestEntities(decConnection);
}
}
Extra Information
There is another method of the LinqToEntitiesDomainService that came in very handy when I was figuring out the above code, this is the OnError method which, when overriden, gives you access to a DomainServiceErrorInfo object, allowing you to see details of any errors that occured.
For example, when I was running this code I had made a spelling mistake in my pre-encrypted connectionString.
Edit
I’ve written a new post about how to put this into a re-usable base class.