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

时间:2012-11-05 13:49:42

标签: c# .net linq entity-framework dynamic

我正在尝试将一些直接构建SQL查询的旧代码转换为Entity Framework,并遇到了许多人似乎都有的问题(从围绕该主题的大量问题来判断):如何在条件表达动态的地方在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语句?

3 个答案:

答案 0 :(得分:2)

在您的情况下,请使用PredicateBuilder,如下所示

另请查看我的博文:Dynamic query with Linq

var outer = PredicateBuilder.True<Entity>();

switch (status) {
        case "0":
            outer = outer.And (p => p.status<0);
            break;
        case "-1":
            outer = outer.And (p => p.status==-1);
            break;
        case "-100":
            outer = outer.And (p => p.status==-100);
            break;
        case "1":
        default:
            outer = outer.And (p => p.status>=0); 
            break;
    }

if (strsearch != "")
        outer = outer.And (p => p.desc.Contains(strsearch ));

dataContext.Entity.Where (outer );

答案 1 :(得分:2)

如果您不想使用外部的东西,那么只需使用流畅的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);
    }
}

答案 2 :(得分:0)

您可以将LinkExtensionLinqKit

一起使用
  using (var context = new workEntities() )
{

    Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
    dictionary["Title"] = new List<string> {  
                    "Network Engineer", 
                    "Security Specialist", 
                    "=Web Developer"
                };
    dictionary["Salary"] = new List<string> { ">=2000" };
    dictionary["VacationHours"] = new List<string> { ">21" };
    dictionary["SickLeaveHours"] = new List<string> { "<5" };                
    dictionary["HireDate"] = new List<string> { 
                    ">=01/01/2000",
                    "28/02/2014" 
                };
    dictionary["ModifiedDate"] = new List<string> { DateTime.Now.ToString() };

    var data = context.Employee.CollectionToQuery(dictionary).ToList();
}