In response to this question:
Better way to write this linq query?
How would i build a dynamic query following the same pattern in that thread?
For example, the signature of the method changes to:
public List<PeopleSearchList> GetPeople(string filter, string searchType, string searchOption)
{
return a new List of type PeopleSearchList
}
So now i am not returning a single array of "Firstnames" etc i am returning a custom class.
The class would look like this:
public class PeopleSearchList
{
public String IdentityCode { get; set; }
public String Firstname { get; set; }
public String Surname { get; set; }
public Int32 LoanCount { get; set; }
public String Group { get; set; }
}
I worked it out.
Just thought i would post the solution for others to see.
public List<PeopleSearchList> GetPeople(string filter, string searchType, string searchOption)
{
IQueryable<Person> query = _context.People;
PropertyInfo property = typeof (Person).GetProperty(searchType);
MethodInfo method = typeof (string).GetMethod(searchOption, new[] {typeof (string)});
query = query.Where(WhereExpression(property, method, filter));
IQueryable<PeopleSearchList> resultQuery = query.Select(p => new PeopleSearchList
{
Firstname = p.Firstname,
Group = p.Level.Year,
IdentityCode = p.IdentityCode,
LoanCount = p.Loans.Count(),
Surname = p.Surname
}
).OrderBy(p => p.Surname);
return resultQuery.ToList();
}
Expression<Func<Person, bool>> WhereExpression(PropertyInfo property, MethodInfo method, string filter)
{
var param = Expression.Parameter(typeof(Person), "o");
var propExpr = Expression.Property(param, property);
var methodExpr = Expression.Call(propExpr, method, Expression.Constant(filter));
return Expression.Lambda<Func<Person, bool>>(methodExpr, param);
}
Related
I want to create generic expression filtering in IQueryable
public class Vehicle
{
public int Id { get; set; }
public string VehicleNO { get; set; }
public int DriverId { get; set; }
public Driver Driver {get;set;}
}
public class Driver
{
public int Id { get; set; }
public string Name { get; set; }
}
operator = "Contain", field name = "Driver.Name", Value filter =
"Micheal"
I don't know how to filter driver name.
Here is my full code
IQueryable<SysClientSiteUser> query = entity.SysClientSiteUsers.Include(i => i.SysClientSiteRole);
Dictionary<string, string> dtFilter = new Dictionary<string, string>();
dtFilter.Add("VehicleNo", "A123");
Dictionary<Type, Func<string, object>> lookup = new Dictionary<Type, Func<string, object>>();
lookup.Add(typeof(string), x => { return x; });
lookup.Add(typeof(long), x => { return long.Parse(x); });
lookup.Add(typeof(int), x => { return int.Parse(x); });
lookup.Add(typeof(double), x => { return double.Parse(x); });
var paramExpr = Expression.Parameter(typeof(Vehicle), "VehicleNo");
var keyPropExpr = Expression.Property(paramExpr, "VehicleNo");
if (!lookup.ContainsKey(keyPropExpr.Type))
throw new Exception("Unknown type : " + keyPropExpr.Type.ToString());
var typeDelegate = lookup[keyPropExpr.Type];
var constantExp = typeDelegate("A123");
var eqExpr = Expression.Equal(keyPropExpr, Expression.Constant(constantExp));
var condExpr = Expression.Lambda<Func<SysClientSiteUser, bool>>(eqExpr, paramExpr);
query = query.Where(condExpr);
for normal field, it's working. But if I want to call Driver name. it's not work. How to call "Driver.Name"?
You can use a helper function to convert a nested property name string to an Expression that accesses that property for a given ParameterExpression and type:
private static Expression MakePropertyExpression<T>(string propertyName, Expression baseExpr) =>
propertyName.Split('.').Aggregate(baseExpr, (b, pname) => Expression.Property(b, pname));
I work with Dapper and I try to create auto-mapped method for inner join.
This is the example of the models:
public class User
{
public long IdUser { get; set; }
public string Email { get; set; }
}
public class Page
{
public long Id { get; set; }
public string Name { get; set; }
public long IdUserCreatedPage { get; set; }
public User UserCreatedPage { get; set; }
}
This is the query:
SELECT * FROM "PAGE" INNER JOIN "USER" ON "PAGE"."IdUserCreatedPage" = "USER"."IdUser"
if I write code mannualy I will write this:
public List<Page> GetPage(IDbConnection dbConnection, string sql)
{
return (List<Page>)dbConnection.Query<Page, User, Page>(sql,
(Page p, User u) =>
{
p.UserCreatedPage = u;
return p;
},
splitOn: "IdUser").ToList();
}
Now, what I want is create dynamically the Func<TFirst, TSecond, TOut> that I need for mapping the object.
Can someone help me? Thank you very much.
P.S. I know that in this case it does not make sense create it dynamically, but this it's only a simply version of all the project of auto-mapping.
SOLUTION
Finally I find the way to do what I want.
This is the code of the function that Generate Func<TFirst, TSecond, TOut>:
public static Func<TFirst, TSecond, TFirst> MappingDynamicFunc<TFirst, TSecond>()
{
ParameterExpression paramFirst = Expression.Parameter(typeof(TFirst), "paramFirst");
ParameterExpression paramSecond = Expression.Parameter(typeof(TSecond), "paramSecond");
MemberExpression memberExpression = Expression.PropertyOrField(paramFirst, "UserCreatedPage");
BinaryExpression assign = Expression.Assign(memberExpression, paramSecond);
LabelTarget labelTarget = Expression.Label(typeof(TFirst));
GotoExpression returnExpression = Expression.Return(labelTarget, paramFirst, typeof(TFirst));
LabelExpression labelExpression = Expression.Label(labelTarget, Expression.Default(typeof(TFirst)));
BlockExpression block = Expression.Block(
assign,
returnExpression,
labelExpression
);
return Expression.Lambda<Func<TFirst, TSecond, TFirst>>(block, new ParameterExpression[] { paramFirst, paramSecond }).Compile();
}
And this is the "GetPage" method:
public List<Page> GetPage(IDbConnection dbConnection, string sql)
{
return (List<Page>)dbConnection.Query<Page, User, Page>(sql,
MappingDynamicFunc<Page, User>(),
splitOn: "IdUser").ToList();
}
Take a look at PredicateBuilder. http://www.albahari.com/nutshell/predicatebuilder.aspx
Here is some pseudo code
var predicate = PredicateBuilder.True<SomeClass>();
if (SomeCondition)
{
var inner = PredicateBuilder.False<SomeClass>();
inner = inner.Or(p => p.Category == "WhatEver");
inner = inner.Or(p => p.Category == "");
predicate = predicate.And(inner);
}
...
var result = MyIEnumerable<SomeClass>.AsQueryable()
.Where(predicate)
.FirstOrDefault();
Class DB_Class {
public int a { get; set; }
public long b { get; set; }
protected string c { get; set; }
protected DateTime F { get; set; }
}
Say there is a class like above, and I want to search in that class and return an IQueryable result because maybe I want to order it later.
I need a function like below---but the below function does NOT work with "integers" or "dateTime", only strings... (because of contains function). I need a more universal function that can take any type--kinda like Python does.
Maybe I need two templates???
public static IQueryable<T> WhereContains<T>(this IQueryable<T> query, string propertyName, string contains)
{
var parameter = Expression.Parameter(typeof(T), "type");
var propertyExpression = Expression.Property(parameter, propertyName);
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var someValue = Expression.Constant(contains, typeof(string));
var containsExpression = Expression.Call(propertyExpression, method, someValue);
return query.Where(Expression.Lambda<Func<T, bool>>(containsExpression, parameter));
}
I want to be able to call like this:
var table = WhereContains<typeoftable>(table, "a", "12");
// or
var table = WhereContains<typeoftable>(table, "c", "Jackso");
// or
var table = WhereContains<typeoftable>(table, "F", "11/23/201");
I am trying to build an expression for sorting, and i wrote code that sorts my list using one property.
But I need to sort it firstly by one property, secondly by another property and so on.
I mean I want to build an expression that will implement something like that: students.OrderBy(fistExpression.Compile()).ThenBy(secondImpression.Complie()).ThenBy(thirdExpression.Compile()).
So how to dynamically put that ThenBy methods?
Here is my code:
Type studentType = typeof(Student);
ParameterExpression studentParam = Expression.Parameter(studentType, "x");
MemberInfo ageProperty = studentType.GetProperty("Age");
MemberExpression valueInNameProperty =
Expression.MakeMemberAccess(studentParam, ageProperty);
Expression<Func<Student, int>> orderByExpression =
Expression<Func<Student, int>>.Lambda<Func<Student, int>>(valueInNameProperty, studentParam);
var sortedStudents = students.OrderBy(orderByExpression.Compile());
My solution:
public static Func<Student, object> BuildPredicate(string propertyName)
{
Type studentType = typeof(Student);
ParameterExpression studentParam = Expression.Parameter(studentType, "x");
MemberInfo ageProperty = studentType.GetProperty(propertyName);
MemberExpression valueInNameProperty = Expression.MakeMemberAccess(studentParam, ageProperty);
UnaryExpression expression = Expression.Convert(valueInNameProperty, typeof (object));
Expression<Func<Student, object>> orderByExpression = Expression.Lambda<Func<Student, object>>(expression, studentParam);
return orderByExpression.Compile();
}
in your expression making code is added casting to object.
That is how you can create a chain of ThenBy:
var sortedStudents = students.OrderBy(BuildPredicate("Age"));
foreach (var property in typeof(Student).GetProperties().Where(x => !String.Equals(x.Name, "Age")))
{
sortedStudents = sortedStudents.ThenBy(BuildPredicate(property.Name));
}
var result = sortedStudents.ToList();
Finally, Student sample class:
public class Student
{
public int Age { get; set; }
public string Name { get; set; }
}
Update:
Another approach is using attributes to mark properies from your Student to use them in OrderBy and ThenBy. Like:
public class Student
{
[UseInOrderBy]
public int Age { get; set; }
[UseInOrderBy(Order = 1)]
public string Name { get; set; }
}
[AttributeUsage(AttributeTargets.Property)]
internal class UseInOrderByAttribute : Attribute
{
public int Order { get; set; }
}
That is how you can build sorting chain using UseInOrderByAttribute:
Type studentType = typeof (Student);
var properties = studentType.GetProperties()
.Select(x => new { Property = x, OrderAttribute = x.GetCustomAttribute<UseInOrderByAttribute>() })
.Where(x => x.OrderAttribute != null)
.OrderBy(x => x.OrderAttribute.Order);
var orderByProperty = properties.FirstOrDefault(x => x.OrderAttribute.Order == 0);
if (orderByProperty == null)
throw new Exception("");
var sortedStudents = students.OrderBy(BuildPredicate(orderByProperty.Property.Name));
foreach (var property in properties.Where(x => x.Property.Name != orderByProperty.Property.Name))
{
sortedStudents = sortedStudents.ThenBy(BuildPredicate(property.Property.Name));
}
var result = sortedStudents.ToList();
Fix: BuildPredicate can be writen without dynamic. BuildPredicate sample code is changed.
I assume that you have private properties that you want to be able to sort.
If you for example have this class:
public class Student
{
public Student (int age, string name)
{
Age = age;
Name = name;
}
private string Name { get; set; }
public int Age { get; set; }
public override string ToString ()
{
return string.Format ("[Student: Age={0}, Name={1}]", Age, Name);
}
}
You can use the following method to build expressions that will get both public and private properties:
public static Func<TType, TResult> CreateExpression<TType, TResult>(string propertyName)
{
Type type = typeof(TType);
ParameterExpression parameterExpression = Expression.Parameter(type, propertyName);
MemberInfo property = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
MemberExpression valueInProperty = Expression.MakeMemberAccess(parameterExpression, property);
return Expression.Lambda<Func<TType,TResult>>(valueInProperty, parameterExpression).Compile();
}
Example of usage:
var students = new [] {
new Student(20, "Ben"),
new Student(20, "Ceasar"),
new Student(20, "Adam"),
new Student(21, "Adam"),
};
var sortedStudents = students
.OrderBy(CreateExpression<Student, string>("Name"))
.ThenBy(CreateExpression<Student, int>("Age"));
sortedStudents.ToList().ForEach(student => Console.WriteLine(student));
/*
Prints:
[Student: Age=20, Name=Adam]
[Student: Age=21, Name=Adam]
[Student: Age=20, Name=Ben]
[Student: Age=20, Name=Ceasar]
*/
I'm trying to build left outer join queries with Linq Expressions but now I really hit the wall.
What I want to accomplish is the following query:
var q =
from i in ProcessInstances
join dof1 in Queries.DataObjectFieldsQuery(this) on new { instanceId = i.ObjectID, dataId = fields[0,0], fieldId = fields[0,1] } equals new { instanceId = dof1.ProcessInstanceObjectID, dataId = dof1.DataID, fieldId = dof1.FieldID } into dofs1
from dof1 in dofs1.DefaultIfEmpty()
join dof2 in Queries.DataObjectFieldsQuery(this) on new { instanceId = i.ObjectID, dataId = fields[1,0], fieldId = fields[1,1] } equals new { instanceId = dof2.ProcessInstanceObjectID, dataId = dof2.DataID, fieldId = dof2.FieldID } into dofs2
from dof2 in dofs2.DefaultIfEmpty()
join dof3 in Queries.DataObjectFieldsQuery(this) on new { instanceId = i.ObjectID, dataId = fields[2,0], fieldId = fields[2,1] } equals new { instanceId = dof3.ProcessInstanceObjectID, dataId = dof3.DataID, fieldId = dof3.FieldID } into dofs3
from dof3 in dofs3.DefaultIfEmpty()
select new WorkitemListModel
{
InstanceId = i.ObjectID,
FormFieldValue1 = dof1.FieldValue,
FormFieldValue2 = dof2.FieldValue,
FormFieldValue3 = dof3.FieldValue,
};
I have defined the following classes:
public class WorkitemListModel
{
public string InstanceId { get; set; }
public string FormFieldValue1 { get; set; }
public string FormFieldValue2 { get; set; }
public string FormFieldValue3 { get; set; }
}
public class DataObjectField
{
public string ProcessInstanceObjectID { get; set; }
public string DataID { get; set; }
public string FieldID { get; set; }
public string FieldValue { get; set; }
}
public class ModelWithFields<TModel>
{
public IEnumerable<DataObjectField> DataObjectFields { get; set; }
public TModel Model { get; set; }
}
public class OuterKeySelector
{
public string instanceId { get; set; }
public string dataId { get; set; }
public string fieldId { get; set; }
}
I created the GroupJoin expression wich gives no compile errors. (I left out som code here):
var q = dc.Instances;
System.Type modelType = typeof(ModelWithFields<>);
System.Type outerKeyType = typeof(WorkitemListModel);
System.Type resultType = modelType.MakeGenericType(outerKeyType);
//... MemberInitExpression and Expression.Bind
q = q.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
"GroupJoin",
new[]
{
typeof(WorkitemListModel),
typeof(DataObjectField),
typeof(OuterKeySelector),
resultType,
},
query.Expression,
Expression.Constant(Queries.DataObjectFieldsQuery(dc)),
Expression.Quote(outerLambda),
Expression.Quote((Expression<Func<DataObjectField,OuterKeySelector>>)(
(DataObjectField dof) =>
new OuterKeySelector
{
instanceId = dof.ProcessInstanceObjectID,
dataId = dof.DataID,
fieldId = dof.FieldID
})),
Expression.Quote(resultLambda)));
// selectmany expression
// collectionSelector lambda -- temp.DataObjectFields.DefaultIfEmpty()
ParameterExpression collectionParameter = Expression.Parameter(resultType, "temp");
// This throw an exception
MethodCallExpression collectionCallExpression =
Expression.Call(
typeof(Queryable),
"DefaultIfEmpty",
new System.Type[]
{
typeof(IQueryable<>).MakeGenericType(typeof(DataObjectField))
},
Expression.Property(collectionParameter, resultType.GetProperty("DataObjectFields")));
But in the SelectMany method I'm trying to add DefaultIfEmpty but I get an exception saying:
No generic method 'DefaultIfEmpty' on
type 'System.Linq.Queryable' is
compatible with the supplied type
arguments and arguments. No type
arguments should be provided if the
method is non-generic.
I've tried the switched the typeparams from IQueryable to IEnumerable and event tried to call Enumerable.DefaultIfEmpty with no luck. Perhaps it's something wrong with the PropertyExpression?
I prefer a different overload for Expression.Call using MethodInfo, here is a simple example I have working.
Expression constant = Expression.Constant(new string[] { "a", "b" });
MethodInfo methodInfo = typeof(Enumerable).GetMethods().FirstOrDefault(c => (c as MethodInfo).Name == "DefaultIfEmpty");
methodInfo = methodInfo.MakeGenericMethod(typeof(string));
MethodCallExpression methodExpression = Expression.Call(methodInfo, constant);
I had defined incorrect type parameter of the Expression.Call method. It wasn't IQueryable<DataObjectField> but only DataObjectField. This is what fixed it.
MethodCallExpression collectionCallExpression =
Expression.Call(
typeof(Enumerable),
"DefaultIfEmpty",
new System.Type[]
{
typeof(DataObjectField)
},
Expression.Property(collectionParameter, newResultType.GetProperty("DataObjectFields"))