2014-05-06 174 views
0

我必須通過一些值搜索一個實體,那些空我不必考慮它們,但其他人我必須使用LIKE語句使用Linq實體。Linq to Entities SQL多個LIKE語句

我想獲得應該與此類似SQL的結果,

... 
WHERE 
(@taxid = '' OR m.taxid LIKE @taxid + '%') AND 
(@personalid = '' OR m.personalid LIKE @personalid + '%') AND 
(@certificate = '' OR m.certificate LIKE @certificate + '%') 

我的LINQ到實體的樣子:

任何線索?

+0

你可以嘗試動態Linq庫它的舊代碼Plex項目 –

回答

0

可以包括參數檢查到查詢

from p in context.Persons 
where (taxId == "" || p.TaxId.StartsWith(taxId)) && 
     (personalId == "" || p.PersonalId.StartsWith(personalId)) && 
     (certificate == "" || p.Certificate.StartsWith(certificate)) 
select p 

或建立查詢動態

IQueryable<Person> query = context.Persons; 

if (taxId != "") 
    query = query.Where(p => p.TaxId.StartsWith(taxId)); 

if (personalId != "") 
    query = query.Where(p => p.PersonalId.StartsWith(personalId)); 

if (certificate != "") 
    query = query.Where(p => p.Certificate.StartsWith(certificate)); 

// etc 
var people = query.ToList(); 

也可考慮使用String.IsNullOrEmpty覈實,如果參數具有價值。

如果您需要生成LIKE '%' + @param + '%'查詢,則使用Contains而不是StartsWith

+1

Apprecaite它! – VAAA