【问题标题】:How to build dynamic linq to sql query in c#?如何在 C# 中构建动态 linq to sql 查询?
【发布时间】:2015-01-16 08:38:51
【问题描述】:

我有一个网页,用户可以通过单击一组 DropDownList 来指定他们的查询。现在我想根据用户的输入构建我的 sql 查询。我使用 System.Linq.Expressions 来做到这一点。

public static IEnumerable<T> FilterTable<T>(List<Filter> filters, Table<T> table) where T : class
    {
        int top;
        IEnumerable<T> query;
        if (filters == null || filters.Count == 0)
        {
            query = table;
        }
        else
        {
            Func<T, bool> lamda = Build<T>(filters, out top);
            if (top > 0)
            {
                query = table.Where(lamda).Take(top);
            }
            else
            {
                query = table.Where(lamda);
            }
        }
        return query;
    }

这种方法确实有效。但它很慢,因为 IIS 首先从数据库服务器获取所有数据,然后应用 where 子句。所以在 IIS 服务器和 db 服务器之间可能会有很多不必要的开销。

那么,有没有更好的方法来做到这一点? linq to sql 中是否有与 System.Linq.Expressions 等价的东西?

【问题讨论】:

    标签: c# asp.net linq


    【解决方案1】:

    使用DynamiclinqlibraryPredicatebuilder 将解决您面临的问题

    查找这两种方法的示例:Dynamic query with Linq


    您的代码的其他问题是您使用了 IEnumerable ,当您从数据库、xmlfile 等数据源获取数据时,它使用了 IQuerable。

    主要区别在于 IEnumerable 将枚举所有元素,而 IQueryable 将根据查询枚举元素,甚至做其他事情。如果 IQueryable Linq Query 被 IQueryProvider 使用,它必须解释或编译才能获得结果。

    阅读示例:IQueryable Vs. IEnumerable in terms of LINQ to SQL queries

    【讨论】:

    • 感谢您的快速回复。我会检查链接,稍后再回来
    猜你喜欢
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-21
    相关资源
    最近更新 更多