开发者

Is there a .NET method to grab the data source for an entity framework connection string?

I want to grab the data source from my connection string. I know I can use

ConfigurationManager.ConnectionStrings["name"].ConnectionString

and extract it out with regex. But, it seems there should be an easy way to grab this开发者_Python百科 data source. I don't want to grab from character position because that would be fragile to any changes in the ordering of the string.

UPDATE

I am using entity framework 4. The connection string is generated and begins with

metadata=res://*/

This appears to complicate things as the suggested object SqlConnectionStringBuilder throws error

"Keyword not supported: 'metadata'."


It's possible to do this (vb.net):

Dim varConnectionString = Web.Configuration.WebConfigurationManager.ConnectionStrings("iSAMDBEntities").ConnectionString
Dim ecb As EntityConnectionStringBuilder = New EntityConnectionStringBuilder(varConnectionString)
varConnectionString = ecb.ProviderConnectionString
Dim varBiulder As SqlConnectionStringBuilder = New SqlConnectionStringBuilder(varConnectionString)
varServidor = varBiulder.DataSource
varBaseDatos = varBiulder.InitialCatalog
varUsuario = varBiulder.UserID
varClave = varBiulder.Password

Hope this helps.


If you are getting metadata error

"Keyword not supported: 'metadata'."

you can first use the EntityConnectionStringBuilder which can take connection string with metadata.

string connectionStringWithMetadata = ConfigurationManager.ConnectionStrings["DbEntities"].ConnectionString;
EntityConnectionStringBuilder entityConnectionStringBuilder = new EntityConnectionStringBuilder(connectionStringWithMetadata);
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder(entityConnectionStringBuilder.ProviderConnectionString);
// And now you can extract parts of the connection string
string dbUserName = connectionStringBuilder.UserID; 
string dbPassword = connectionStringBuilder.Password;


I found it hidden in the context.

EntityContextName context = new EntityContextName();
string datasourceName = context.Connection.DataSource;


Yes, there is a SqlConnectionStringBuilder class that should get you what you want.

Have a look at the MSDN documentation, this should get you close, here is the full detail, you will most likely just need to enumerate through the keys.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜