Getting The Database Connection String From an ObjectContext

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:

01.var dataTable = new DataTable
02.    {
03.        Columns = { new DataColumn("Value", typeof(string)) }
04.    };
05.dataTable.Rows.Add("first row");
06.dataTable.Rows.Add("second row");
07.dataTable.Rows.Add("third row");
08. 
09.//
10.// EF does not support table-valued parameters, so we'll do it ourselves
11.//
12.using (var ctx = new MyObjectContext())
13.using (var cn = new SqlConnection(((System.Data.EntityClient.EntityConnection)ctx.Connection).StoreConnection.ConnectionString))
14.using (var cmd = cn.CreateCommand())
15.{
16.    cmd.CommandText = "SomeRealyCoolStoredProcedure";
17.    cmd.CommandType = CommandType.StoredProcedure;
18. 
19.    cmd.Parameters.AddWithValue("ID", 123456);
20.    cmd.Parameters.AddWithValue("ValuesTable", dt).TypeName = "MyTableType";
21. 
22.    cn.Open();
23.    cmd.ExecuteNonQuery();
24.}

Freelance full-stack .NET and JS developer and architect. Located near Cologne, Germany.

1 thought on “Getting The Database Connection String From an ObjectContext

Leave a Reply

Your email address will not be published. Required fields are marked *