【发布时间】:2014-01-10 14:19:32
【问题描述】:
我想知道我该怎么做? 事实是我有一个带有搜索条件的对象(一些要搜索的字段表示条件)。我需要根据条件构建查询,但它使用 AND 加入 where。 这就是我所拥有的:
public class SearchCriteria
{
public SearchCriteria()
{
this.Theme = new HashSet<int>();
}
public string KeyWord { get; set; }
public bool? ChildrenFirstCycle { get; set; }
public bool? ChildrenSecondCycle { get; set; }
public bool? Primary { get; set; }
public bool? Secondary { get; set; }
public bool? BachelorArts { get; set; }
public bool? BachelorHumanities { get; set; }
public bool? BachelorScience { get; set; }
public bool? University { get; set; }
public bool? MediumLevelCycle { get; set; }
public bool? HighLevelCycle { get; set; }
public int? DistrictID { get; set; }
public int? CountyID { get; set; }
public int? MunicipalID { get; set; }
public ICollection<int> Theme { get; set; }
}
public IEnumerable<School> GetAllEscuelasBySearchCriteria(SearchCriteria searchCriteria)
{
var Query = this._repository.Retrieve();
if (!string.IsNullOrWhiteSpace(searchCriteria.KeyWord))
{
Query = Query.Where(p => p.Name.Contains(searchCriteria.KeyWord) || p.Grade.Contains(searchCriteria.KeyWord) || p.Email.Contains(searchCriteria.KeyWord) || p.Address.Contains(searchCriteria.KeyWord) || p.Code.Contains(searchCriteria.KeyWord));
}
//Rest of condition
if (RestConditions)
{
Query = Query.Where(p=> REST CONDITIONS);
}
//I need to create a list of func expression and add each expression pass the condition and then a foreach and do an OR for all in List of FUNC
if (searchCriteria.InfantilFirstCycle.HasValue && searchCriteria.InfantilFirstCycle.Value != false)
{
Query = Query.Where(p => (p.value1 > 0 || p.value2 > 0 || p.value3 > 0));
}
if (searchCriteria.InfantilSecondCycle.HasValue && searchCriteria.InfantilSecondCycle.Value != false)
{
Query = Query.Where(p => (p.value4 > 0 || p.value5 > 0 || p.value6 > 0));
}
if (searchCriteria.Primary.HasValue && searchCriteria.Primary.Value != false)
{
Query = Query.Where(p => (p.value7 > 0 || p.value8 > 0 || p.value9 > 0 || p.value10 > 0 || p.value11 > 0 || p.value13 > 0 || p.value14 > 0));
}
return Query.Distinct().OrderBy(c=>c.Name).ToList();
}
【问题讨论】:
-
我遇到了这个确切的问题,最终使用了动态 linq。github.com/kahanu/System.Linq.Dynamic
-
我试过但说 base {System.Exception} = {"LINQ to Entities 不支持 LINQ 表达式节点类型 'Invoke'。"}
标签: entity-framework lambda where func