动态LINQ to Entities,如何基于变量构建查询

时间:2013-06-26 20:21:42

标签: c# linq-to-entities dynamic-programming

我需要构建的查询是:

query = query.Where(s => 
           (
              (s.Title.Contains(title1) && s.EpisodeTitle.Contains(episodeTitle1))
               ||
              (s.Title.Contains(title2) && s.EpisodeTitle.Contains(episodeTitle2)))
            );

唯一的问题是,s.Title和s.EpisodeTitle是动态的。

意味着以下变量可以成为查询的一部分:

(string title1 = null,
  string title2 = null,
  string episodeTitle1 = null,
  string episodeTitle2 = null,
  string genre = null,
  string directorName = null,
  string releaseYear = null,
  string seasonEpisode = null,
  string showTypeDescription = null)

e.g。

query = query.Where(s => 
           (
              (s.DirectorName.Contains(directorName) && s.ShowTypeDescription.Contains(ShowTypeDescription))
               ||
              (s.releaseYear.Contains(releaseYear) && s.genre.Contains(genre)))
            );

在任何类型的组合中。

如何在不考虑每个单一可能性的情况下构建此查询?

2 个答案:

答案 0 :(得分:3)

如果您只需要AND逻辑,则可以针对需要搜索的每个属性重复调用.Where()

if(title != null) query = query.Where(x=>x.Title == title);
if(genre != null) query = query.Where(x=>x.Genre == genre);

如果您的查询始终具有某种结构,并且您希望忽略空搜索值,则可以执行一个大查询,但使用null检查将属性比较短路。

query = query.Where(s => 
  (
    ((title1 == null || s.Title.Contains(title1)) 
        && (episodeTitle1 == null || s.EpisodeTitle.Contains(episodeTitle1))
     ||
    ((title2 == null || s.Title.Contains(title2)) 
       && (episodeTitle2 == null || s.EpisodeTitle.Contains(episodeTitle2))))
        );

但是,如果您需要完全控制查询,那么您需要查看使用PredicateBuilder或System.Linq.Expressions来构建特定查询以搜索必要的属性。这是一个关于Linq.Expressions的有用教程 - http://msdn.microsoft.com/en-us/library/vstudio/bb882637.aspx

答案 1 :(得分:0)

最佳解决方案是将linqExtensionLINQKIT一起使用。

    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();
}