We use Entity Framework 5, but have a requirement to ALSO use a normal database connection from the application for some custom SQL we need to perform.
So, I am creating
//Entity Framework 5
myContext.Database.Connection.ConnectionString
//Entity Framework 6
myContext.Database.Connection.ConnectionString
//Entity Framework Core 1
myContext.Database.GetDbConnection().ConnectionString
I had this problem too, to solve the problem you can do this:
SqlConnection con = context.Database.Connection as SqlConnection;
SqlCommand command = new SqlCommand(sql, con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.HasRows)
{
while (reader.Read())
{
//read your fields
}
reader.NextResult();
}
con.Close();
Here is a generic way of getting the connection string:
public string GetConnString<T>(T ent)
where T : ObjectContext
{
EntityConnection ec = (EntityConnection)ent.Connection;
SqlConnection sc = (SqlConnection)ec.StoreConnection;
return sc.ConnectionString;
}
Then to use it would be:
MyEntities ent = new MyEntities();
String ConnString = GetConnString(ent);
In current versions of EF you can find the property here: dbContext.Database.TransactionManager.ConnectionString
Do you mean, can you use a SqlConnection with your EF DbContext?
The DbContext class has a constructor where you can pass in a SqlConnection, and then tell EF whether or not it owns it.
var YourContext = new YourContext(SqlConnection, true);
You can get the connectionstring used by EF by using the following:
MyDbContext.Database.Connection.ConnectionString
Or as mark says you can initalise the context with a sqlconnection