Using ServiceStack Autoquery with Type Values โ€‹โ€‹That Do Not Implement IConvertible

I tried to use AutoQuery with a parameter NodaTime.LocalDatein the query parameter, and I get the following exception when I try to filter using this date field, in particular >MyDate=2020-01-01(the order does not change):

[MyEndpoint: 5/23/2016 4:19:51 PM]: [REQUEST: {}] System.InvalidCastException: Invalid cast from 'System.String' to 'NodaTime.LocalDate'. at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) at ServiceStack.TypedQuery`2.AppendUntypedQueries(SqlExpression`1 q, Dictionary`2 dynamicParams, String defaultTerm, IAutoQueryOptions options, Dictionary`2 aliases) at ServiceStack.TypedQuery`2.CreateQuery(IDbConnection db, IQueryDb dto, Dictionary`2 dynamicParams, IAutoQueryOptions options) at ServiceStack.AutoQuery.CreateQuery[From](IQueryDb`1 dto, Dictionary`2 dynamicParams, IRequest req) at ServiceStack.AutoQueryServiceBase.Exec[From](IQueryDb`1 dto) at ServiceStack.Host.ServiceRunner`1.Execute(IRequest request, Object instance, TRequest requestDto)

I tracked it down to this line of code , which uses Convert.ChangeType(...)because it NodaTime.LocalDateis struct, not enum:

var value = strValue == null ? 
      null 
    : isMultiple ? 
      TypeSerializer.DeserializeFromString(strValue, Array.CreateInstance(fieldType, 0).GetType())
    : fieldType == typeof(string) ? 
      strValue
    : fieldType.IsValueType && !fieldType.IsEnum ? //This is true for NodaTime.LocalDate
      Convert.ChangeType(strValue, fieldType) :    //NodaTime.LocalDate does not implement IConvertible, so this throws
      TypeSerializer.DeserializeFromString(strValue, fieldType);

I use my NodaTime ServiceStack serialization library , so the behavior TypeSerializer.DeserializeFromString(strValue, fieldType)is what I really want in this case.

The workarounds that I see are as follows:

  • MyDateDateBetween=2020-01-01,9999-12-31 , , ()
  • DateTime NodaTime.LocalDate ( NodaTime.LocalDate)
  • AutoQuery ( )
  • NodaTime.LocalDate IConvertible ()

, IConvertible?

+4
1

ChangeTo() , IConvertible :

public static object ChangeTo(this string strValue, Type type)
{
    if (type.IsValueType && !type.IsEnum
        && type.HasInterface(typeof(IConvertible)))
    {
        try
        {
            return Convert.ChangeType(strValue, type);
        }
        catch (Exception ex)
        {
            Tracer.Instance.WriteError(ex);
        }
    }
    return TypeSerializer.DeserializeFromString(strValue, type);
}

AutoQuery, , NodaTime LocalDate TypeSerializer.

v4.0.57, MyGet.

+4

All Articles