I’m trying to add the orderby expression on the fly. But when the query below is executed I get the following exception:
System.NotSupportedException: Unable
to create a constant value of type
‘Closure type’. Only primitive types
(‘such as Int32, String, and Guid’)
are supported in this context.
The strange thing is, I am query exactly those primitive types only.
string sortBy = HttpContext.Current.Request.QueryString["sidx"];
ParameterExpression prm = Expression.Parameter(typeof(buskerPosting), "posting");
Expression orderByProperty = Expression.Property(prm, sortBy);
// get the paged records
IQueryable<PostingListItemDto> query =
(from posting in be.buskerPosting
where posting.buskerAccount.cmsMember.nodeId == m.Id
orderby orderByProperty
//orderby posting.Created
select new PostingListItemDto { Set = posting }).Skip<PostingListItemDto>((page - 1) * pageSize).Take<PostingListItemDto>(pageSize);
Hope somebody can shed some light on this!
You basically can’t use query expressions like this, due to the way they’re translated. However, you can do it explicitly with extension methods:
The tricky bit is getting the right expression tree type – that’ll come in an edit 🙂
EDIT: The edit will be somewhat delayed for various reasons. Basically you may need to call a generic method using reflection, as
Queryable.OrderByneeds a genericExpression<Func<TSource, TKey>>and although it looks like you know the source type at compile-time, you may not know the key type. If you do know it’ll always be ordering by (say) an int, you can use:EDIT: Okay, it looks like I had time after all. Here’s a short example of calling
OrderByusing reflection:You could easily refactor
CallOrderByinto an extension method (e.g.OrderByProperty) like this:Your original code then becomes:
(Apologies for the formatting involving horizontal scrollbars… I’ll reformat later if anyone cares. Or you could do it for me if you have enough rep 😉