Created
November 27, 2012 15:23
-
-
Save rippo/4154778 to your computer and use it in GitHub Desktop.
For stackover flow question http://programmers.stackexchange.com/questions/176826/creating-a-predicate-builder-extension-method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Calling code | |
[NHibernateActionFilter] | |
public JsonResult ListContact(long id, [DataSourceRequest] DataSourceRequest request) | |
{ | |
IQueryable<Contact> contactList; | |
if (id > 0) | |
contactList = session.Query<Contact>().Where(y => y.ContactEmailList.Any(x => x.EmailList.Id == id && y.Client.Id == UserHelper.Id)); | |
else | |
contactList = session.Query<Contact>().Where(y => y.Client.Id == UserHelper.Id); | |
return contactBuilder2.FilterContacts(contactList, request); | |
} | |
//Note: when calling this I get Remotion.Linq.Utilities.ArgumentTypeException | |
Expected a type implementing IEnumerable<T>, but found 'Domain.Model.Entities.Contact'. Parameter name: expression | |
namespace Cms.Mvc.Helpers.PredicateBuilders | |
{ | |
public class ContactBuilder2 : Controller | |
{ | |
public JsonResult FilterContacts(IQueryable<Contact> contactList, DataSourceRequest request) | |
{ | |
var page = request.Page - 1; | |
if (page < 0) page = 0; | |
if (request.Filters.Any()) | |
{ | |
//Single column | |
var filter = request.Filters[0] as FilterDescriptor; | |
if (filter != null) | |
{ | |
contactList = contactList.FilterContacts(filter); | |
} | |
//multiple columns | |
var f = request.Filters[0] as CompositeFilterDescriptor; | |
if (f != null) | |
{ | |
for (int i = 0; i < f.FilterDescriptors.Count; i++) | |
{ | |
var f2 = f.FilterDescriptors[i] as FilterDescriptor; | |
if (f2 != null) | |
{ | |
contactList = contactList.FilterContacts(f2); | |
} | |
} | |
} | |
} | |
var total = contactList.Count(); | |
if (request.Sorts.Any()) | |
{ | |
switch (request.Sorts[0].Member) | |
{ | |
case "Name": | |
contactList = request.Sorts[0].SortDirection == ListSortDirection.Ascending | |
? contactList.OrderBy(w => w.Firstname).ThenBy(w => w.Lastname) | |
: contactList.OrderByDescending(w => w.Firstname).ThenByDescending(w => w.Lastname); | |
break; | |
case "Company": | |
contactList = request.Sorts[0].SortDirection == ListSortDirection.Ascending | |
? contactList.OrderBy(w => w.Company).ThenBy(w => w.Firstname).ThenBy(w => w.Lastname) | |
: contactList.OrderByDescending(w => w.Company).ThenBy(w => w.Firstname).ThenBy(w => w.Lastname); | |
break; | |
default: | |
contactList = contactList.OrderBy(w => w.Firstname).ThenBy(w => w.Lastname).ThenBy(w => w.Company); | |
break; | |
} | |
} | |
else | |
contactList = contactList.OrderBy(w => w.Firstname).ThenBy(w => w.Lastname).ThenBy(w => w.Company); | |
var list = contactList.Take(request.PageSize).Skip(page * request.PageSize).ToList().ToPagedList(page, request.PageSize, total); | |
//var list = contactList.Take(20).Skip(1 * 25).ToList().ToPagedList(1, 25, total); | |
var json = new ContactListDto | |
{ | |
Total = total, | |
Data = list.Select(item => new JsonContactSearchDto { Id = item.Id, Name = item.Firstname + " " + item.Lastname, Company = item.Company }).ToList() | |
}; | |
return Json(json, JsonRequestBehavior.AllowGet); | |
} | |
} | |
public static class ContactBuilderExtensions | |
{ | |
public static IQueryable<Contact> FilterContacts(this IQueryable<Contact> contactList, FilterDescriptor filter) | |
{ | |
return contactList.Where(contact => | |
contact.GetFilterStrings(filter.Member).Any(s => s.IsAMatch(filter.Operator, filter.Value.ToString()))); | |
} | |
private static bool IsAMatch(this string filterString, FilterOperator filterOperator, string value) | |
{ | |
switch (filterOperator) | |
{ | |
case FilterOperator.StartsWith: | |
return filterString.StartsWith(value); | |
case FilterOperator.Contains: | |
return filterString.Contains(value); | |
case FilterOperator.IsEqualTo: | |
return filterString == value; | |
} | |
throw new ArgumentException(string.Format("Invalid Operator: {0}", filterOperator)); | |
} | |
private static IEnumerable<string> GetFilterStrings(this Contact contact, string member) | |
{ | |
switch (member) | |
{ | |
case "Name": | |
return new[] | |
{ | |
contact.Firstname, | |
contact.Lastname, | |
contact.Firstname + " " + contact.Lastname | |
}; | |
case "Company": | |
return new[] | |
{ | |
contact.Company | |
}; | |
} | |
throw new ArgumentException(string.Format("Invalid Member: {0}", member)); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Expected a type implementing IEnumerable<T>, but found 'Domain.Model.Entities.Contact'. Parameter name: expression | |
ERRORSHELPABOUT | |
Remotion.Linq.Utilities.ArgumentTypeException | |
Expected a type implementing IEnumerable<T>, but found 'Domain.Model.Entities.Contact'. Parameter name: expression | |
Remotion.Linq.Parsing.ParserException: Cannot parse expression 'contact' as it has an unsupported type. Only query sources (that is, expressions that implement IEnumerable) and query operators can be parsed. ---> Remotion.Linq.Utilities.ArgumentTypeException: Expected a type implementing IEnumerable<T>, but found 'Domain.Model.Entities.Contact'. | |
Parameter name: expression | |
at Remotion.Linq.ReflectionUtility.GetItemTypeOfIEnumerable(Type enumerableType, String argumentName) | |
at Remotion.Linq.Parsing.Structure.IntermediateModel.MainSourceExpressionNode..ctor(String associatedIdentifier, Expression expression) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseNonQueryOperatorExpression(Expression expression, String associatedIdentifier) | |
--- End of inner exception stack trace --- | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseNonQueryOperatorExpression(Expression expression, String associatedIdentifier) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseNode(Expression expression, String associatedIdentifier) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, String associatedIdentifier) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseNode(Expression expression, String associatedIdentifier) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, String associatedIdentifier) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseNode(Expression expression, String associatedIdentifier) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseTree(Expression expressionTree) | |
at Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot) | |
at Remotion.Linq.Parsing.ExpressionTreeVisitors.SubQueryFindingExpressionTreeVisitor.CreateSubQueryNode(MethodCallExpression methodCallExpression) | |
at Remotion.Linq.Parsing.ExpressionTreeVisitors.SubQueryFindingExpressionTreeVisitor.VisitExpression(Expression expression) | |
at Remotion.Linq.Parsing.ExpressionTreeVisitor.VisitLambdaExpression(LambdaExpression expression) | |
at Remotion.Linq.Parsing.ExpressionTreeVisitor.VisitExpression(Expression expression) | |
at Remotion.Linq.Parsing.ExpressionTreeVisitors.SubQueryFindingExpressionTreeVisitor.VisitExpression(Expression expression) | |
at Remotion.Linq.Parsing.ExpressionTreeVisitors.SubQueryFindingExpressionTreeVisitor.Process(Expression expressionTree, INodeTypeProvider nodeTypeProvider) | |
at Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.ProcessArgumentExpression(Expression argumentExpression) | |
at Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.<Parse>b__0(Expression expr) | |
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() | |
at System.Linq.Buffer`1..ctor(IEnumerable`1 source) | |
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source) | |
at Remotion.Linq.Parsing.Structure.MethodCallExpressionParser.Parse(String associatedIdentifier, IExpressionNode source, IEnumerable`1 arguments, MethodCallExpression expressionToParse) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, String associatedIdentifier) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseNode(Expression expression, String associatedIdentifier) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseMethodCallExpression(MethodCallExpression methodCallExpression, String associatedIdentifier) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseNode(Expression expression, String associatedIdentifier) | |
at Remotion.Linq.Parsing.Structure.ExpressionTreeParser.ParseTree(Expression expressionTree) | |
at Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot) | |
at NHibernate.Linq.NhRelinqQueryParser.Parse(Expression expression) | |
at NHibernate.Linq.NhLinqExpression.Translate(ISessionFactoryImplementor sessionFactory) | |
at NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryIdentifier, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory) | |
at NHibernate.Engine.Query.HQLExpressionQueryPlan.CreateTranslators(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) | |
at NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) | |
at NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) | |
at NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters) | |
at NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow) | |
at NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression queryExpression) | |
at NHibernate.Linq.DefaultQueryProvider.PrepareQuery(Expression expression, IQuery& query, NhLinqExpression& nhQuery) | |
at NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression) | |
at NHibernate.Linq.DefaultQueryProvider.Execute[TResult](Expression expression) | |
at System.Linq.Queryable.Count[TSource](IQueryable`1 source) | |
at Cms.Mvc.Helpers.PredicateBuilders.ContactBuilder2.FilterContacts(IQueryable`1 contactList, DataSourceRequest request) in e:\WebSites\PC\PC-mail\Website\CMS.Website\Cms.Mvc\Helpers\PredicateBuilders\ContactBuilder.cs:line 161 | |
at Cms.Mvc.Controllers.AJaxClientController.ListContact(Int64 id, DataSourceRequest request) in e:\WebSites\PC\PC-mail\Website\CMS.Website\Cms.Mvc\Controllers\AjaxClientController.cs:line 92 | |
at lambda_method(Closure , ControllerBase , Object[] ) | |
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) | |
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) | |
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) | |
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() | |
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) | |
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() | |
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) | |
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() | |
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() | |
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() | |
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) | |
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() | |
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) | |
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<>c__DisplayClass2a.<BeginInvokeAction>b__20() | |
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) | |
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() | |
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) | |
at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) | |
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) | |
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() | |
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) | |
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) | |
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() | |
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) | |
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) | |
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) | |
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) | |
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() | |
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) | |
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) | |
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() | |
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment