Getting The Database Connection String From an ObjectContext
Photo by To Tao on Pexels
The trick here is to cast the Connection property of the ObjectContext to the type System.Data.EntityClient.EntityConnection. Then you can access the StoreConnection property:
var dataTable = new DataTable
{
Columns = { new DataColumn("Value", typeof(string)) }
};
dataTable.Rows.Add("first row");
dataTable.Rows.Add("second row");
dataTable.Rows.Add("third row");
//
// EF does not support table-valued parameters, so we'll do it ourselves
//
using (var ctx = new MyObjectContext())
using (var cn = new SqlConnection(((System.Data.EntityClient.EntityConnection)ctx.Connection).StoreConnection.ConnectionString))
using (var cmd = cn.CreateCommand())
{
cmd.CommandText = "SomeRealyCoolStoredProcedure";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("ID", 123456);
cmd.Parameters.AddWithValue("ValuesTable", dt).TypeName = "MyTableType";
cn.Open();
cmd.ExecuteNonQuery();
}
Category: SQL Server and Entity Framework