Efcore: System.InvalidCastException : Unable to cast object of type 'Microsoft.Data.SqlClient.SqlConnection' to type 'System.Data.SqlClient.SqlConnection'.

Created on 24 Sep 2019  路  5Comments  路  Source: dotnet/efcore

Steps to reproduce

C# DbConnection dbConnection = context.Database.GetDbConnection(); // System.Data.Common SqlConnection sqlConnection= (SqlConnection)dbConnection; // System.Data.SqlClient
Second line throws an exception:

System.InvalidCastException : Unable to cast object of type
'Microsoft.Data.SqlClient.SqlConnection' to type 'System.Data.SqlClient.SqlConnection'.

I need this for bulk.WriteToServer() since _SqlConnection_ is type of the first argument in _SqlBulkCopy_ constructor.

Further technical details

EF Core version: NET Core 3.0
Database provider: in library System.Data.SqlClient is used,
--------------------- while TestProject has also Microsoft.EntityFrameworkCore.SqlServer
Target framework: (.NET Standard 2.1)
Operating system: Windows 10
IDE: (Visual Studio 2019 16.3)

closed-question customer-reported

Most helpful comment

After reading following blog: introducing-the-new-microsoftdatasqlclient
I have solved the issue by replacing _System.Data.SqlClient_ nuGet with _Microsoft.Data.SqlClient_.

All 5 comments

Microsoft.EntityFrameworkCore.SqlServer depends on Microsoft.Data.SqlClient hence the cast is invalid.
@bricelam - Is there a way to use SqlServer package with System.Data.SqlClient?

You need to create a new SqlConnection object. There's no way to convert between the two.

We have https://github.com/aspnet/EntityFrameworkCore/issues/15758 for re-introducing a System.Data.SqlClient.dll based provider.

@borisdj AFAIK, Microsoft.Data.SqlClient also has SqlBulkCopy. Can you just remove System.Data.SqlClient in favor of the new Microsoft.Data.SqlClient?

After reading following blog: introducing-the-new-microsoftdatasqlclient
I have solved the issue by replacing _System.Data.SqlClient_ nuGet with _Microsoft.Data.SqlClient_.

Precisely what I did.
Can be closed.

Was this page helpful?
0 / 5 - 0 ratings