Вопрос

The Microsoft Enterprise Library Data Access Application Block contains the following method:

private static IDataParameter[] CreateParameterCopy(DbCommand command)
{
    IDataParameterCollection parameters = (IDataParameterCollection)command.Parameters;
    IDataParameter[] parameterArray = new IDataParameter[parameters.Count];
    parameters.CopyTo(parameterArray, 0);

    return CachingMechanism.CloneParameters(parameterArray);
}

If command.Parameters is a TdParameterCollection (a Teradata .NET provider class that implements IDataParameterCollection), then parameters.CopyTo(parameterArray, 0) throws an InvalidCastException: "Unable to cast object of type System.Data.IDataParameter[] to type Teradata.Client.Provider.TdParameter[]".

My first question:

How and why is this happening?

The exception message suggests that the parameters have been copied successfully to parameterArray, but there is an attempt afterwards to convert parameterArray from IDataParameter[] to TdParameter[]. (In any case, TdParameter implements IDataParameter.)

My second question:

Any ideas how to fix this without using concrete types?

Это было полезно?

Решение

The problem is in the internal code of the CopyTo method.

MSDN says:

The type of the source ICollection cannot be cast automatically to the type of the destination array.

That means that the array must be able to convert without explicit conversion. Otherwise the method call will fail.

Instead of using CopyTo, you should use a foreach and copy them by hand one by one.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top