Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get SqlConnection from DbConnection

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!

like image 278
Dirk Boer Avatar asked Jun 03 '13 20:06

Dirk Boer


People also ask

How do I get SqlConnection?

Creating a SqlConnection Object A SqlConnection is an object, just like any other C# object. Most of the time, you just declare and instantiate the SqlConnection all at the same time, as shown below: SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

What is SqlConnection and SqlCommand?

A SqlConnection object represents a unique session to a SQL Server data source. With a client/server database system, it is equivalent to a network connection to the server. SqlConnection is used together with SqlDataAdapter and SqlCommand to increase performance when connecting to a Microsoft SQL Server database.

What is SqlConnection in Ado net?

ADO.NET SqlConnection Class. It is used to establish an open connection to the SQL Server database. It is a sealed class so that cannot be inherited. SqlConnection class uses SqlDataAdapter and SqlCommand classes together to increase performance when connecting to a Microsoft SQL Server database.


1 Answers

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; 
like image 170
haim770 Avatar answered Oct 06 '22 04:10

haim770