I keep getting the exception
The SqlParameterCollection only accepts non-null SqlParameter type objects, not String objects
, while execut
I ran into the same issue, but mine was doing an object[2] = object[1] as SqlParameters, similar to what was being tried.
Just to add to the thread, I have this simple object array of SqlParameters added from a method like this,
private SqlParameter GetGenericParamsObject(string name, object data)
{
return new SqlParameter(name, SetSqlDataType(data.GetType().ToString())) { Direction = Input, Value = data };
}
Where there is a simple switch for the SetSqlDataType(), i.e. SqlDbType.Int is one of the return types to set it.
Then I run
private static void ExecuteSqlCommand(DbContext dbContext, string sql, params object[] sqlParameters)
{
try
{
if (dbContext.Database.Connection.State == ConnectionState.Closed)
dbContext.Database.Connection.Open();
var cmd = dbContext.Database.Connection.CreateCommand();
cmd.CommandText = sql;
foreach (var param in sqlParameters)
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
This helps with casting to the proper data type and moves the param name, datatype and object out of the command method for easier debugging and then just adding the entire SqlParameter to the cmd.Parameters.