Is it at all possible to use something like a switch statement in a compiled query for linq to entities/sql? For example when returning sorted records from the database, I would like to use a switch-like statement within one compiled query to sort on different properties, instead of having 开发者_开发问答to write 2 compiled queries (ascending & descending) for every property you might want to sort on, which can be up to 10 compiled queries for even a simple sortable grid.
In T-SQL this would be easy with a case statement, as I would imagine a construct like this is supported in most databases, so why would it not be supported in linq/entity framework.
Any solution for this?
As kyndigs refers to in his comment, the only solution is to fake a switch statement with the ? :
tertiary operator:
internal static readonly Func<MyEntities, long, MessageSortField, int, int, IQueryable<Model.Message>> MessagesPagedSortedAscQuery =
CompiledQuery.Compile((MyEntities db, long folderId, MessageSortField sortField, int skip, int take) =>
(
sortField == MessageSortField.Date ? db.Messages.Where(e => e.FolderId == folderId).OrderBy(m => m.Date).Skip(skip).Take(take) :
sortField == MessageSortField.Subject ? db.Messages.Where(e => e.FolderId == folderId).OrderBy(m => m.Subject).Skip(skip).Take(take) :
sortField == MessageSortField.From ? db.Messages.Where(e => e.FolderId == folderId).OrderBy(m => m.From).Skip(skip).Take(take) :
db.Messages.Where(e => e.FolderId == folderId).Skip(skip).Take(take)
));
精彩评论