我正在构建适用于单个实体的动态 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();