4

I am building dynamic linq expressions which is working fine for a single entity. For example: I have a class called Employee and 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; }
}

I need to get all the the employees and empeduinfo class starts with "x"

I prepared expression for startswith("x")

var temp= entities.employees.Include("EmpEduInfo").Where(mydynamicexpression);

In this case it is filtering only parent table not on child.

I need to prepare generic expression so than i need to filter both parent and child objects dynamically.

Without using expression I know a solution:

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();

using expressions I am building generic expression to provide dynamic advance search rather than writing in each and every entity.

Here is my expression details

            // 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();
4

2 に答える 2

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;
于 2013-01-10T09:14:29.660 に答える
0

私はEF 4.0で試していましたが、同じものにDBエクステンションを書き込んでいます。

オプションは EF 4.1 で提供されます

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-応用

ありがとう。

于 2013-01-31T04:11:20.020 に答える