Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the connection string for Entity Framework using the POCO template

I use Entity Framework and I need to get my connection string so I can construct a context.

I am using the POCO template. My context object has:

string ConnectionString = "name=MyAppConfigConnectionStringPropertyHere"

So when I try to just construct my context it says

"The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid"

I saw in this answer that indicated that there is a GetConnectionString() method. But googling has not lead me to the reference I need to add to get that method (it is not in my project by default).

So, I can't think that I am the first one who wants to get a connection string for entity framework using the POCO templates. How have others done this? I guess I can just read in the whole app.config file and parse it out. But it seems like it should not be that hard.

Any hints would be great!

like image 376
Vaccano Avatar asked Jul 05 '11 18:07

Vaccano


3 Answers

For people not using EF 4.1 here is the easiest way to do it that I know of:

using System.Data.EntityClient;

public static string GetConnectionString(ObjectContext context)
{
    return ((EntityConnection)context.Connection).StoreConnection.ConnectionString;
}
like image 156
dyslexicanaboko Avatar answered Nov 15 '22 15:11

dyslexicanaboko


For entity framework 6.0, following code gives current ConnectionString.

context.Database.Connection.ConnectionString
like image 42
Yauvaraj Rimal Avatar answered Nov 15 '22 14:11

Yauvaraj Rimal


I get the DB connection like this

 var connection = (SqlConnection)_context.Database.Connection;

Then from connection you get the ConnectionString and other info you need

like image 23
Daveo Avatar answered Nov 15 '22 13:11

Daveo