Get SqlConnection from DbConnection

c# connection-string entity-framework mvc-mini-profiler sql

Question

I have an Extension method on DbContext where I want to do a SqlBulkCopy. Therefore I need a SqlConnection. The connection from the DbContext is from the type DbConnection though. Among a few other things I tried this:

var connection = new SqlConnection( dbContext.Database.Connection.ConnectionString);

Problem is that the password is missing (probably for security reasons).

Another thing that I tried is upcasting:

var bulk_copy = new SqlBulkCopy( (SqlConnection)dbContext.Database.Connection );

That actually presumes the DbConnection is a SqlConnection. In this very specific case it already goes wrong. I'm using the MVC MiniProfiler that wraps the connection into an EFProfiledDbConnection. EFProfiledDbConnection does not inherit from SqlConnection.

Any other ideas? Thanks in advance!

1
24
6/3/2013 8:29:34 PM

Popular Answer

Well, if both can share the same Connection String then I guess they're both SqlConnection.

Try this instead:

var connection = rep.Database.Connection as SqlConnection;
19
4/23/2017 9:08:00 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow