I'm trying to accomplish a page in asp.net mvc to filter a sql server view. My page looks like this:
Each "filter" is a SearchViewModel
which has a class definition like this:
public class SearchViewModel
{
//Property has a property called "SqlColumnName"
public Property Property { get; set; }
public Enums.SearchOperator Operator { get; set; }
public string Value { get; set; }
}
When I submit the form a IList<SearchViewModel>
will be passed to the controller. Until here everything works fine.
In the controller class I'm passing the IList<SearchViewModel>
to a helper method:
public static Func<ViewEvents, bool> GetLamdaExpression(IEnumerable<SearchViewModel> lstSearchViewModels)
{
Expression dynamiclambda = null;
Expression call;
//creating the first part of the lambda expression (select.Where(ve => ve.Name == "exp"))
// this function returns "(ve =>" as typeof ViewEvents
var param = Expression.Parameter(typeof(ViewEvents), "viewEvents");
//storing functions for use with the combiner
var containsMethod = typeof(string).GetMethod("Contains");
var equalsMethod = typeof(string).GetMethod("Equals", new[] { typeof(string) });
var startsWithMethod = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
var endsWithMethod = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
var toLowerMethod = typeof(string).GetMethod("ToLower", Type.EmptyTypes);
foreach (var lstSearchViewModel in lstSearchViewModels.Where(svm => svm.Value != null))
{
//get the property info of the property from the SearchViewModel
var property = typeof(ViewEvents).GetProperty(lstSearchViewModel.Property.SqlColumnName);
if (property == null)
throw new ObjectNotFoundException($"The object {typeof(ViewEvents).ToString()} does not have a property called {lstSearchViewModel.Property.SqlColumnName}");
//create the second part of the lambda expression
//this function returns "ve.Property"
var propertyAccess = Expression.MakeMemberAccess(param, property);
//add the "toLower" function to the property
//this function returns "(ve.Property.ToLower()"
var toLower = Expression.Call(propertyAccess, toLowerMethod);
//adds the operator to the lambda expression
//functions return p.ex.: ve.Property.ToLower().Contains("value")
// or ve.Property.ToLower().Equals("value") != true (NotEquals)
switch (lstSearchViewModel.Operator)
{
case Enums.SearchOperator.Contains:
call = Expression.Call(toLower, containsMethod,
Expression.Constant(lstSearchViewModel.Value.ToLower()));
break;
case Enums.SearchOperator.ContainsNot:
call = Expression.Call(toLower, containsMethod,
Expression.Constant(lstSearchViewModel.Value.ToLower()));
//adding ..Contains("value") != true ; used like .ContainsNot("value")
call = Expression.NotEqual(call, Expression.Constant(true));
break;
case Enums.SearchOperator.StartsWith:
call = Expression.Call(toLower, startsWithMethod,
Expression.Constant(lstSearchViewModel.Value.ToLower()));
break;
case Enums.SearchOperator.EndsWith:
call = Expression.Call(toLower, endsWithMethod,
Expression.Constant(lstSearchViewModel.Value.ToLower()));
break;
case Enums.SearchOperator.Equals:
call = Expression.Call(toLower, equalsMethod,
Expression.Constant(lstSearchViewModel.Value.ToLower()));
break;
case Enums.SearchOperator.EqualsNot:
call = Expression.Call(toLower, equalsMethod,
Expression.Constant(lstSearchViewModel.Value.ToLower()));
//adding ..Equals("value") != true ; used like .NotEquals("value")
call = Expression.NotEqual(call, Expression.Constant(true));
break;
default:
throw new ArgumentOutOfRangeException();
}
//Combind the filters with an and combiner
dynamiclambda = dynamiclambda == null ? call : Expression.And(dynamiclambda, call);
}
if (dynamiclambda == null)
{
throw new InvalidOperationException("No dynamiclambda was created");
}
//gets the actual lambda expression like: (ve => ve.Property.ToLower().Contains("value") AND ve.Property.ToLower().Equals("value") ...
var predicate = Expression.Lambda<Func<ViewEvents, bool>>(dynamiclambda, param);
var compiled = predicate.Compile();
return compiled;
}
Now when I enter a value of "1" in the input field next to "Typ", the variable predicate
of the function contains the following value:
{viewEvents => viewEvents.Level.ToLower().Contains("1")}
Later on in the controller the compiled predicate will be used to query the view of the database with entity framework 6 like this:
var lambda = Helper.GetLamdaExpression(lstSearchViewModels);
var eventEntries = DataBase.ViewEvents.Where(lambda);
and here comes the "error". No rows were returned from the database. But when I change the code to
var lambda = Helper.GetLamdaExpression(lstSearchViewModels);
var eventEntries = DataBase.ViewEvents.Where(viewEvents => viewEvents.Level.ToLower().Contains("1"));
The expected number of rows are returned.
Anyone an idea where the bug is?
The problem is that you must use an Expression<Func<>>
and not a Func<>
. The first contains an expression tree that can be parsed to convert the Where
clause into SQL. This can't be done with the latter.
Besides you're overcomplicating: you can return a lambda directly, without doing so much work. This is a simplified example:
public Expression<Func<ViewEvents, bool>> GetEqualIdLambda(int id)
{
return (ViewEvents ve) => ve.Id == id;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.