多个EF中的条件

可能重复:
条件Linq查询

使用Entity Framework 4.0

我有这样的搜索条件

在此处输入图像描述

有四个字段允许用户过滤搜索。 条件都是AND 。 如果文本框值为String.Empty或者下拉列表值为All ,则结果必须省略相应的filter。 可以在存储过程中执行此操作,但我无法在Linq2SQL / Entity Framework方案中模仿这一点。

我的问题是,如何在Linq中根据一些输入值省略IEnumerable.Where?

你可以链接你的where子句。 您只需要一个IQueryable数据源。

 var filteredData = _repository.GetAll(); //If your data source is IEnumerable, just add .AsQueryable() to make it IQueryable if(keyWordTextBox.Text!="") filteredData=filteredData.Where(m=>m.Keyword.Contains(keyWordTextBox.Text)); if(LocationDropDown.SelectedValue!="All") filteredData=filteredData.Where(m=>m.Location==LocationDropDown.SelectedValue)); ... etc.... 

因为它是IQueryable,所以在绑定数据之前不会获取数据,因此它只会提取您需要的数据。

假设您的代码中的位置和类别由ID标识(id是combobox项目中的值属性),您可以执行类似于

 function GetItems(string keyword, string consultant, int? locationId, int categoryId){ using(MyContextEntities context = new MyContextEntities()){ return context.Items.Where(item => (string.IsNullOrEmpty(keyword) || item.Text.Contains(keyword)) && (string.IsNullOrEmpty(consultant) || item.Consultant.Contains(consultant)) && (!locationId.HasValue || item.Location.Id == locationId.Value) && (!categoryId.HasValue || item.Category.Id == categoryId.Value) ); } } 

看看PredicateBuilder 。 它允许你做这样的事情:

 IQueryable SearchProducts (params string[] keywords) { var predicate = PredicateBuilder.True(); foreach (string keyword in keywords) { string temp = keyword; if(temp != String.Empty || temp != "All") predicate = predicate.And(e => e.???.Contains (temp)); } return dataContext.??.Where (predicate); } 

这样做的灵活方法是单独构建where子句。

本文将向您介绍如何执行此操作。 初始设置它需要一些工作。 但它值得。

你可以做这样的事情。

 var abc = from al in myEntity.a where (field == string.Empty ? al.field == string.Empty : al.field == field) select new { al.field1, al.field2, al.field3 }; 

我认为Skip While and Take While可能会对您的情况有所帮助

http://msdn.microsoft.com/en-us/vcsharp/aa336757#SkipWhileSimple