Error when using dictionary in a Iqueryable.Select() method to project columns chosen at runtime

Asked

Viewed 57 times

3

The code fragment below aims to use the Select() method to perform generic column projections in a query, according to a list of column names provided. The program works fine if all columns are 'string' type, but triggers the exception below when some column is of a different type, like 'Guid''.

Expression of type 'System.Guid' cannot be used for Parameter of type 'System.Object' of method 'Void Add(System.String, System.Object)

How can I solve this problem?

public static IQueryable EscolherColunas<T>(this IQueryable<T> baseQuery, String[] columns) where T : class 
{
    var parameter = Expression.Parameter(typeof(T), "t");
    var addMethod = typeof(Dictionary<string, object>).GetMethod("Add");
    List<ElementInit> dicadds = new List<ElementInit>();
    foreach (var column in columns)
    {
        var eKey = Expression.Constant(column);
        var eValue = Expression.Property(parameter, column);
        var eAdd = Expression.ElementInit(addMethod, eKey, eValue);
        dicadds.Add(eAdd);
    }
    var dicinit = Expression.ListInit(Expression.New(typeof(Dictionary<string, object>)), dicadds);
    var selector = Expression.Lambda<Func<T, dynamic>>(dicinit, parameter);
    return baseQuery.Select(selector);
}
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.