Linq对儿童实体的表达

时间:2013-01-10 07:11:26

标签: linq entity-framework

我正在构建动态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();

2 个答案:

答案 0 :(得分:2)

您可以使用Expression

查看编译器生成的IQueryable:
IQueryable<Employee> query = 
  from ee in entities.Employee ...

var expression = query.Expression;

在调试器中查看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;

答案 1 :(得分:0)