當我們使用Entity Framework + Linq時
要做and的運算是很簡單的
目標.Where().Where().Where().....即可
但如果我們要串接Or運算呢?
很可惜Linq本身先天並不支援
但我們可以透過LinqKit的幫助
假設我們想輸出的SQL為
SELECT *
FROM [MySampleTable]
where [NAME] like '%1%' or [NAME] like '%2%' or [NAME] like '%3%'
先從Nuget安裝LinqKit
public List<MySampleTable> GetTable(List<string> strList)
{
//假設 strList 的內容是 1, 2, 3
using (SampleContext dbContext = ContextInit())
{
IQueryable<MySampleTable> result = dbContext.MySampleTable;
/*
SELECT *
FROM [MySampleTable]
where [NAME] like '%1%' or [NAME] like '%2%' or [NAME] like '%3%'
*/
var predicate = PredicateBuilder.New<MySampleTable>();
// 1, 2, 3
foreach (var str in strList)
{
predicate = predicate.Or(q => q.NAME != null && q.NAME.Contains(str));
}
result = result.AsExpandable().Where(predicate);
return result.ToList();
}
}