How to solve - The SqlParameterCollection only accepts non-null Microsoft.Data.SqlClient.SqlParameter type objects, not System.Data.SqlClient.SqlParameter objects.' - Error in .Net
The error message System.InvalidCastException: "The SqlParameterCollection
only accepts non-null Microsoft.Data.SqlClient.SqlParameter
type objects, not System.Data.SqlClient.SqlParameter
objects" occurs when you try to add a System.Data.SqlClient.SqlParameter
object to a Microsoft.Data.SqlClient.SqlParameterCollection
object.
This error occurs because the Microsoft.Data.SqlClient
and System.Data.SqlClient
namespaces represent two different ADO.NET providers for SQL Server, and the two providers use different types for their SQL parameters.
To fix this error, you need to make sure that you use the correct type of SQL parameter object when you are working with a Microsoft.Data.SqlClient.SqlParameterCollection
. If you are using Microsoft.Data.SqlClient
, you should use Microsoft.Data.SqlClient.SqlParameter
objects. If you are using System.Data.SqlClient
, you should use System.Data.SqlClient.SqlParameter
objects.
Here's an example of how to create a Microsoft.Data.SqlClient.SqlParameter
object and add it to a Microsoft.Data.SqlClient.SqlParameterCollection
object:
c#using Microsoft.Data.SqlClient;
// create a SqlConnection object
using SqlConnection connection = new SqlConnection("your_connection_string_here");
// create a SqlCommand object
using SqlCommand command = new SqlCommand("SELECT * FROM MyTable WHERE MyColumn = @param1", connection);
// create a SqlParameter object and add it to the SqlCommand's parameters collection
SqlParameter parameter = new SqlParameter("@param1", SqlDbType.NVarChar, 50);
parameter.Value = "my_parameter_value";
command.Parameters.Add(parameter);
Note that in this example, we are using the Microsoft.Data.SqlClient.SqlParameter
object instead of the System.Data.SqlClient.SqlParameter
object, since we are working with a Microsoft.Data.SqlClient.SqlParameterCollection
object.
Comments
Post a Comment