Linq to Entities SQL多个LIKE语句

时间:2014-05-06 15:02:27

标签: linq entity-framework linq-to-entities

我必须通过某些值搜索实体,空的我不必考虑它们,但其他我必须使用Linq to Entities的LIKE语句。

我想要获得的结果应该类似于这个SQL,

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

我的Linq to Entities看起来像:

persons = context.Persons.Where(e => e.TaxId.Contains(taxId) && e.PersonalId.Contains(personalId) && e.Certificate.Contains(certificate)).ToList();

有任何线索吗?

1 个答案:

答案 0 :(得分: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

相关问题