我正在构建动态
linq表达式,它适用于单个实体.
例如:
我有一个名为Employee和empeduinfo的类
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class EmpEduInfo
{
public int Id { get; set; }
public string Name { get; set; }
public int EmpId { get; set; }
}
我需要让所有的员工和empeduinfo类以“x”开头
我为startswith准备了表达式(“x”)
var temp= entities.employees.Include("EmpEduInfo").Where(mydynamicexpression);
在这种情况下,它仅过滤不在子项上的父表.
我需要准备通用表达式,因此我需要动态地过滤父对象和子对象.
不使用表达式我知道一个解决方案:
var temp= (from ee in entities.Employee.Include("EmpEduInfo").Where(x => x.name.StartsWith("t"))
where ee.EmpEduInfo.Where(x => x.name.StartsWith("t")).Count()>0
select ee).ToList();
使用表达式我正在构建通用表达式以提供动态高级搜索,而不是在每个实体中写入.
这是我的表达细节
// Get the method information for the String.StartsWith() method
MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
// Build the parameter for the expression
ParameterExpression empparam= Expression.Parameter(typeof(employee), "ename");;
// Build the member that was specified for the expression
MemberExpression field = Expression.PropertyOrField(empparam, "name");
// Call the String.StartsWith() method on the member
MethodCallExpression startsWith = Expression.Call(field, mi, Expression.Constant("t"));
var namelamda = Expression.Lambda<Func<employee, bool>>(startsWith, new ParameterExpression[] { empparam });
var temp = entities.employees.Include("empedudetails").Where(namelamda).ToList();
最佳答案 您可以查看编译器使用IQueryable生成的Expression:
IQueryable<Employee> query =
from ee in entities.Employee ...
var expression = query.Expression;
查看调试器中的表达式,看看你需要生成什么 – LINQPad对此有好处.
您可能希望先简化查询:
IQueryable<Employee> query =
from ee in entities.Employee.Include("EmpEduInfo")
where
ee.name.StartsWith("t") &&
ee.EmpEduInfo.Any(x => x.name.StartsWith("t"))
select ee;