Search code examples
c#sqlgenericssqlparameter

Cannot implicitly convert type 'System.Collections.Generic.List<System.Data.SqlClient.SqlParameter>' to 'System.Data.SqlClient.SqlParameter'


For the code:

sqlParameter = parameterSettings.GetParameters<T>(table, config);

I'm receiving the error:

Error 1 Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Data.SqlClient.SqlParameter' C:\Users\jonathan.cameron\Documents\Visual Studio 2013\Projects\DataGenerator\DataGenerator\Methods\Query.cs 99 28 DataGenerator

The method signature for GetParameters:

public List<SqlParameter> GetParameters<T>(T table, Config config)

The rest of the code

public int RunInsertQuery<T>(bool returnPrimary, SqlCommand cmd, Config config, 
             ParameterSettings parameterSettings, SqlParameter sqlParameter, 
                T table)
{
        // Used to create an INSERT Query
    Query query = new Query();

        // Pass item that needs to be inserted into SQL
    cmd.CommandText = query.InsertQuery<T>(table, config);
        // If the primary key needs to be returned...
    if(returnPrimary == true)
    {
        cmd.CommandText += "SELECT CAST(scope_identity() AS int)";
    }            
        // Obtain column names/data types/values into the SqlParameter object
    sqlParameter = parameterSettings.GetParameters<T>(table, config);

        // Check for null in Sql Parameter values, apply DBNull.Value, return parameters to
        // SqlCommand instance
    cmd.Parameters.AddRange(parameterSettings.NullValueCheck(sqlParameter).ToArray());

        // if returnPrimary is truen, return the primary key while executing 
        // the sql parameter
    if (returnPrimary)
    {
        return (int)cmd.ExecuteScalar();
    }
    else
        cmd.ExecuteNonQuery();
    return 1;            
}

Solution

  • The GetParameters method returns a List and thus cannot be assigned to an SqlParameter field. This field needs to be of type List<SqlParameter> or you need to select one value from the return value of the GetParameters method.