Reputation: 6109
I'm using EF with 2 databases - with SQL CE and SQL Server.
Is there a way to know which connection type is used at runtime? I mean, if I have only ObjectContext in some place (already initialized with some connection string), can I get the database type from it (is it Compact or SQL Server at the moment)?
Thanks
Upvotes: 0
Views: 142
Reputation: 122654
You can check the Connection Property, which should return an EntityConnection; from there you must check its StoreConnection which will be the "real" database connection.
From there, you can either check the ConnectionString, which will tell you the provider, or simply check the type of the provider connection itself with is
or GetType
. If it's SQL Server it will be a SqlConnection
, and if it's SQL CE it will be a SqlCeConnection
.
This looks like an ugly hack because it is; if you're looking for a way to do this without an ugly hack, don't bother - the ObjectContext
is explicitly designed not to leak any information about the connection unless you know exactly what to ask for. By contrast, here's all the hoops you would have to jump through to check it via the app config:
static string GetProviderName(ObjectContext context)
{
string entityConnectionString = GetEntityConnectionString(context);
return !string.IsNullOrEmpty(entityConnectionString) ?
GetProviderConnectionString(entityConnectionString) : null;
}
static string GetEntityConnectionString(ObjectContext context)
{
var match = Regex.Match(context.Connection.ConnectionString,
@"name=(?<name>[^;]+)", RegexOptions.Compiled);
string connectionStringName = match.Success ?
match.Groups["name"].Value : null;
return ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
static string GetProviderConnectionString(string entityConnectionString)
{
var match = Regex.Match(entityConnectionString,
@"provider=(?<provider>[^;]+)", RegexOptions.Compiled);
return match.Success ? match.Groups["provider"].Value : null;
}
Once any solution starts to involve regexes, I tend to look for a straighter path, and in this case, that's the type casting you say you'd prefer not to use. Pick your poison.
Be careful how you use either of the above approaches. EF4 is designed around persistence ignorance and you should be trying to avoid any logic that's specific to the connection type, because you really have no idea how it will be configured (maybe tomorrow it will be an Oracle connection). I believe that the provider-specific code resides mainly in the QueryProvider.
Upvotes: 3