在操作数据库时,经常需要对某些查询进行“SQL拼串”,比如需要动态指定order by的字段啦,或者是where后面的查询条件啦,等等。这么做在SQL中可以一劳永逸,避免再因为查询需求的改变去写更多的方法和代码。但是在LINQ中怎么进行拼串呢?虽然LINQ中也支持SQL查询,并且可以进行处理,不过我希望的是,可以像SQL一样动态的去处理查询字符串,而不希望在LINQ中,出现SQL,那是件很恶心的事情

解决方案 »

  1.   

    HIHI又见面了,因为没有系统的学习过LINQ,所以只是边用边学,在遇到问题的时候,希望大家多指点。
    麻烦楼上给个实例- -
      

  2.   

    比如,我需要一个需要改变orderby字段条件的一个方法,像这样的        public List<T> GetSuperAdmin(字段 值)
            {
                return (from o in DB.Table orderby 值 select o).ToList();
            }该怎么做呢?有没有实例来个?
      

  3.   

    LZ参考微软给的例子,在网上下载:CSharpSamples,里面有专门提到用LinQ动态查询的。
    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");
    .....................
      

  4.   

    其实就是改变排序的列,在LINQ中怎么做?
    我需要将这些东西都封装起来,然后只提供可供调用的方法然后传参即可。
      

  5.   

    简单的说就是,比如有两个列,一个是ID,一个是日期,然后,我怎么写一个方法,通过传参去像重组SQL语句一样的,决定是用ID还是用日期,是正序还是倒序?
    如果再加一个条件,比如where什么的,我又该怎么处理呢?
      

  6.   

    你看看我写的文章 http://blog.csdn.net/fuadam/archive/2008/04/17/2302473.aspx
    比如你 order by  u => u.Name
    你就可以得到Name,你就可以动态拼sql语句了。
      

  7.   

    你如果对linq够了解可以自己写 where select seletmany这些东西。不仅仅能处理数据库操作还能处理很多东西
      

  8.   

    16742685我博客里写着了,你上次不发个贴文table是什么类型吗,我在那个回复里告诉你要看什么书了