c# - Linq-to-Entities 查询中的动态条件

标签 c# .net linq entity-framework dynamic

我正在尝试将一些直接构建 SQL 查询的旧代码转换为 Entity Framework,并且遇到了一个许多人似乎都有的问题(从围绕该主题的大量问题来看):如何表达动态 where 条件在 linq 中。

如何使用 linq 查询来表达以下代码:

    switch (status) {
        case "0":
            sqlwhere = " WHERE status < 0 ";
            break;
        case "-1":
            sqlwhere = " WHERE status = -1 ";
            break;
        case "-100":
            sqlwhere = " WHERE status = -100 ";
            break;
        case "1":
        default:
            sqlwhere = " WHERE status >= 0 ";
            break;
    }

    if (strsearch != "")
        sqlwhere += " AND desc LIKE '%" + strsearch + "%' ";

    string sqlc = "SELECT top 10 * FROM c " + sqlwhere + " order by date desc";

我在其他帖子中读到了有关 PredicateBuilder 和动态 Linq 扩展的内容,但我认为像这样的简单案例在没有外部库的情况下也是可以解决的。

使用 .net 4.5、EF 5.0、C#,这是否可以在不为每个案例构建完整的 linq 语句的情况下以“动态”方式完成?

最佳答案

如果您不想使用外部的东西,那么只需使用流畅的 API:

var query = db.YourTableName
              .Where(x => x.desc.Contains(strsearch));

switch (status) {
   case "0":
        query = query.Where(x => x.status < 0);
        break;
   case "-1":
        query = query.Where(x => x.status == -1);
        break;
   case "-100":
        query = query.Where(x => x.status == -100);
        break;
   case "1":
   default:
        query = query.Where(x => x.status >= 0);
        break;
}

var result = query.OrderByDescending(x => x.date)
                  .Take(10);

BTW 您可以创建按状态过滤的扩展方法。您的查询将如下所示:

var query = db.YourTableName
              .FilterByStatus(status)
              .Where(x => x.desc.Contains(strsearch))
              .OrderByDescending(x => x.date)
              .Take(10);

扩展方法:

public static IQueryable<YourType> FilterByStatus(this IQueryable<YourType> query, 
                                                  string status)
{

    switch (status) {
       case "0":
            return query.Where(x => x.status < 0);            
       case "-1":
            return query.Where(x => x.status == -1);
       case "-100":
            return query.Where(x => x.status == -100);
       case "1":
       default:
            return query.Where(x => x.status >= 0);
    }
}

关于c# - Linq-to-Entities 查询中的动态条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13233461/

相关文章:

c# - 具有可变数量参数的匿名方法

c# - 在 MVVM WPF 应用程序中打开新窗口

c# - 如何将数字转换为价格范围

c# - 使用 iTextSharp 创建多页 pdf

c# - 使用 WebImage.Resize 时出现内存不足异常

c# - 在 WPF 中查看 Word 文档

c# - 什么时候需要使用 x86 或 x64 目标平台?

.net - 为 SignalR 实现背板和消息总线

c# - 如何在锯齿状数组中查找唯一值

c# - 赋值的左侧必须是变量