mvc实体框架选择动态where子句

时间:2017-04-05 14:05:51

标签: entity-framework select union

我正在使用 App。

我有select条指令,我需要有一个动态where条件。

通常情况下,您有一个由“aaaa bbbb cccc”之类的字符串组成的过滤器。我需要提供包含所有过滤字符串或部分过滤字符串的所有数据。

我做了Split功能,但是很难得到所有可能的组合。

我宁愿使用Store Procedure。但它的用途是使用实体框架。

到目前为止,我做到了这一点。

 public IEnumerable<UploadSearch> GetUploadsBySearch(string search)
        {
            IEnumerable<UploadSearch> viewModel = (from uploads in _db.Uploads
                                                   .Where(p => p.ProcessState_id == Security.APPROVED && p.Finder.Contains(search))
                                                   .OrderByDescending(p => p.UploadDate)
                                                   select new UploadSearch
                                                   {
                                                       User_id = uploads.User_id,
                                                       UserName = uploads.Users.Name,
                                                       UserLastName = uploads.Users.LastName,
                                                   });
                                                   

我通过字符串loop添加了一条for指令,

 string[] param = search.Replace("  "," ").Split(' ');
            string _param = "";
             int large = param.Length; 

for (int i=0;i<large-1;i++)
            {
            _param +=param[i] ' ' + param[i + 1];
           IEnumerable<UploadSearch> _viewModel = (from uploads in _db.Uploads
                                                   .Where(p => p.ProcessState_id == Security.APPROVED && p.Finder.Contains(_param))
                                                   .OrderByDescending(p => p.UploadDate)
                                                   select new UploadSearch
                                                   {
                                                       User_id = uploads.User_id,
                                                       UserName = uploads.Users.Name,
                                                       UserLastName = uploads.Users.LastName,
                                                   });
 viewModel = viewModel.Union(_viewModel);                                                   
                                                   }
                                                   

我使用Union条款。

但还有另一种方法可以做到。

任何想法?

1 个答案:

答案 0 :(得分:0)

你应该使用LinqKit,它有一个PredicateBuilder类,允许你动态构建查询

https://github.com/scottksmith95/LINQKit#predicatebuilder

IQueryable<Product> SearchProducts (params string[] keywords)
{
  var predicate = PredicateBuilder.New<Product>();

  foreach (string keyword in keywords)
  {
    string temp = keyword;
    predicate = predicate.Or (p => p.Description.Contains (temp));
  }
  return dataContext.Products.Where (predicate);
}