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.}
Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s