i have an form to search criteria, and i use PredicateBuilder to combine all criteras to an WHere Expression - and the EF generate sql for evaluate in DataBase side.
for allow the user choise between equal, start with, end with and contains, i use asterisk wildcard.
this my code:
var predicate = LinqKit.PredicateBuilder.New<PersonEntity>(true);
{
var arg = parameters.Name;
arg = arg.Trim();
var start = arg[0] == '*';
var end = arg[arg.Length - 1] == '*';
arg = arg.Trim('*');
if (start && end)
predicate.And(x => x.Name.Contains(arg));
else if (start)
predicate.And(x => x.Name.StartsWith(arg));
else if (end)
predicate.And(x => x.Name.EndsWith(arg));
else
predicate.And(x => x.Name == arg);
}
{
var arg = parameters.Address;
arg = arg.Trim();
var start = arg[0] == '*';
var end = arg[arg.Length - 1] == '*';
arg = arg.Trim('*');
if (start && end)
predicate.And(x => x.Address.Contains(arg));
else if (start)
predicate.And(x => x.Address.StartsWith(arg));
else if (end)
predicate.And(x => x.Address.EndsWith(arg));
else
predicate.And(x => x.Address == arg);
}
end ect...
i want write a generic helper function, for simple use:
predicate.And(Helper.AddStringCompareCriteria(x => x.Name, parameters.Name);
predicate.And(Helper.AddStringCompareCriteria(x => x.Address, parameters.Address);
my try for now:
public static class Helper
{
static Type strType = typeof(string);
static MethodInfo strStart = typeof(string).GetMethod("StartsWith");
static MethodInfo strEnd = typeof(string).GetMethod("EndsWith");
static MethodInfo strContains = typeof(string).GetMethod("Contains");
static MethodInfo strEquals = typeof(string).GetMethod("Equals");
static MethodInfo RightMethod(bool start, bool end)
{
if (start && end)
return strContains;
if (start)
return strStart;
if (end)
return strEnd;
else
return strEquals;
}
public static Expression<Func<T, bool>> AddStringCompareCriteria<T, TResult>(Expression<Func<T, TResult>> member, string toComprae)
{
var arg = toComprae;
arg = arg.Trim();
var start = arg[0] == '*';
var end = arg[arg.Length - 1] == '*';
arg = arg.Trim('*');
MethodInfo method = RightMethod(start, end);
ParameterExpression entityParam = Expression.Parameter(typeof(T), "entity");
return Expression.Lambda<Func<T, bool>>(
Expression.Call(/* get-member-here?*/ , method, new[] { Expression.Constant(arg) }),
entityParam);
}
}
I now do not know how to access the selected member (by the function expression), And I'm not sure I'm in the right direction, I'd be happy to help!.