在操作数据库时,经常需要对某些查询进行“SQL拼串”,比如需要动态指定order by的字段啦,或者是where后面的查询条件啦,等等。这么做在SQL中可以一劳永逸,避免再因为查询需求的改变去写更多的方法和代码。但是在LINQ中怎么进行拼串呢?虽然LINQ中也支持SQL查询,并且可以进行处理,不过我希望的是,可以像SQL一样动态的去处理查询字符串,而不希望在LINQ中,出现SQL,那是件很恶心的事情
调试欢乐多
麻烦楼上给个实例- -
{
return (from o in DB.Table orderby 值 select o).ToList();
}该怎么做呢?有没有实例来个?
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;namespace System.Linq.Dynamic
{
public static class DynamicQueryable
{
public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values) {
return (IQueryable<T>)Where((IQueryable)source, predicate, values);
} public static IQueryable Where(this IQueryable source, string predicate, params object[] values) {
if (source == null) throw new ArgumentNullException("source");
if (predicate == null) throw new ArgumentNullException("predicate");
LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable), "Where",
new Type[] { source.ElementType },
source.Expression, Expression.Quote(lambda)));
} public static IQueryable Select(this IQueryable source, string selector, params object[] values) {
if (source == null) throw new ArgumentNullException("source");
if (selector == null) throw new ArgumentNullException("selector");
.....................
我需要将这些东西都封装起来,然后只提供可供调用的方法然后传参即可。
如果再加一个条件,比如where什么的,我又该怎么处理呢?
比如你 order by u => u.Name
你就可以得到Name,你就可以动态拼sql语句了。