The code fragment below is intended to use the Select () method to perform generic column projections on a query, according to a list of given column names. The program works fine if all the columns are of type 'string', but triggers the exception below when some column is of a different type, like 'Guid'.
Expression of type 'System.Guid' can not 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);
}