Did you know that connection string builders will parse connection strings not just create them?
OK. So this one was new on me. Thanks to my colleague down the hall, Alazel Acheson, (being able to say that, by the way, has got to be one of the coolest things about working at Microsoft -- it's great to be surrounded by very smart people) I was able to quickly solve a little problem that has been bugging me lately. It was such an easy solution and a bit unexpected that I thought I'd share it.
Background: The EF uses a connection string for many things including a way to specify the location of your metadata, which store provider you want to use and the connection string for that stored provider. If you really want to talk to the database, you need all those things, but if all you want to do is play with some objects in the ObjectContext/ObjectStateManager, then all you really need is the metadata. Well, actually you also need to know which provider as well for some esoteric reasons we won't discuss right now, but you very specifically do NOT need to know the provider connection string--which is a good thing in some scenarios because provider connection strings can contain sensitive information (like a username and password).
I've got just one of those scenarios that I'm playing around with these days. Part of my solution runs on the middle tier and has a full connection string, but for another part of my solution I want to serialize some data down to a client box which has the entity framework and everything on it but doesn't need or have access to the database. To make my solution work, I'd like to remove the provider connection string from my overall connection string and only serialize that in order to make sure I don't send any sensitive info to the client.
Problem: I really didn't want to write a bunch of code to parse the connection string. Sure we have just that kind of code down in EntityClient, but this solution I'm building lives outside the entity framework, so I needed something publically accessible and easy to use.
Solution: EntityConnectionStringBuilder (and all the other connection string builders) has a constructor overload that takes a connection string. If you use that constructor, then it will parse everything out for you so that you can easily modify things and then reconstitute the connection string. In my case, the code looks something like this:
var csBuilder = new EntityConnectionStringBuilder(context.Connection.ConnectionString);
csBuilder.ProviderConnectionString = null;
this.connectionString = csBuilder.ConnectionString;
Couldn't be easier.
Comments
- Anonymous
January 09, 2008
PingBack from http://geeklectures.info/2008/01/09/did-you-know-that-connection-string-builders-will-parse-connection-strings-not-just-create-them/