The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects

By FoxLearn 12/25/2024 4:36:41 AM   18
If you're working with Entity Framework Core (EF Core) and encounter the following exception when executing a query with parameters:
System.InvalidCastException: The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects

The error you see happens because the SqlParameterCollection expects a SqlParameter object from the Microsoft.Data.SqlClient library, not the one from System.Data.SqlClient. This discrepancy occurs because EF Core uses Microsoft.Data.SqlClient for SQL Server interactions, which is a more modern and optimized package compared to the older System.Data.SqlClient.

Solution: Switch to Microsoft.Data.SqlClient.SqlParameter

To resolve this exception, you simply need to ensure you're using the correct SqlParameter class. EF Core works with Microsoft.Data.SqlClient.SqlParameter (part of the Microsoft.Data.SqlClient package), which is compatible with SQL Server databases.

var nameParameter = new Microsoft.Data.SqlClient.SqlParameter("@Name", "Bob");
dbContext.Database.ExecuteSqlInterpolated($"INSERT INTO dbo.Names (Name) VALUES ({nameParameter})");

We create a SqlParameter instance from Microsoft.Data.SqlClient to represent a parameter (@Name), then pass this parameter to an interpolated SQL query using ExecuteSqlInterpolated, which helps execute the SQL with the provided parameters safely.

If your project does not yet reference Microsoft.Data.SqlClient, you'll need to install the appropriate NuGet package.

To install the package, open the Package Manager Console in Visual Studio (Navigate to View > Other Windows > Package Manager Console) and run the following command:

Install-Package Microsoft.Data.SqlClient

This will ensure you have the correct version of SqlClient that EF Core expects when interacting with SQL Server.