日期:2014-05-20  浏览次数:20831 次

LINQ动态条件查询问题?
这两天在研究LINQ动态查询,但是自己把网上拿来东西在根据自己需要在变通一下就有问题了,请帮忙解决下,我已在本机上调试很多次都有问题的~

C# code

IQueryable<Customer> custs = db.Customers;  
改成IQueryable<Customer> custs = db.Customers.Where(c=>c.City=="London");//先筛选再动态查询
ParameterExpression param = 
    Expression.Parameter(typeof(Customer), "c");
Expression selector = Expression.Property(param,
    typeof(Customer).GetProperty("ContactName"));
Expression pred = Expression.Lambda(selector, param);
Expression expr = Expression.Call(typeof(Queryable), "Select",
    new Type[] { typeof(Customer), typeof(string) },
    Expression.Constant(custs), pred);
IQueryable<string> query = db.Customers.AsQueryable()
    .Provider.CreateQuery<string>(expr);   //经过上面的筛选调试结果为空?请问能否这样?
System.Data.Common.DbCommand cmd = db.GetCommand(query);
Console.WriteLine(cmd.CommandText);


IQueryable<Customer> custs = db.Customers;
ParameterExpression param =
   Expression.Parameter(typeof(Customer), "c");
Expression left = Expression.Property(param,
    typeof(Customer).GetProperty("City"));
Expression right = Expression.Constant("London");
Expression filter = Expression.Equal(left, right);
Expression pred = Expression.Lambda(filter, param);
MethodCallExpression whereCallExpression = Expression.Call(
    typeof(Queryable), "Where",
    new Type[] { typeof(Customer) },
    Expression.Constant(custs), pred);
//OrderBy(ContactName => ContactName)
MethodCallExpression orderByCallExpression = Expression.Call(
    typeof(Queryable), "OrderBy",
    new Type[] { typeof(Customer), typeof(string) }, 
    whereCallExpression,
    Expression.Lambda(Expression.Property
    (param, "ContactName"), param));
//生成动态查询
IQueryable<Customer> query = db.Customers.AsQueryable()
    .Provider.CreateQuery<Customer>(orderByCallExpression);


上面代码实现了where orderby动态查询,请问怎么同时实现SELECT where 或 SELECT where orderby查询,我试了很多次修改,都不行?现在感觉LINQ动态查询很难满足平时项目中的需要,请问有什么好的办法吗?

------解决方案--------------------
你写一个sql,一下自己就明白了。

你写这一大堆莫名其妙的“Linq”代码,我真的很同情Linq啊。这是把Linq抬高了之后重重地扔在阴沟里捧杀。呵呵呵呵。