【问题标题】:Linq to Entities SQL Multiple LIKE statementsLinq to Entities SQL 多个 LIKE 语句
【发布时间】:2014-05-06 15:02:27
【问题描述】:

我必须通过一些值来搜索实体,那些为空的我不必考虑它们,但其他的我必须使用 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 Entity 看起来像:

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

有什么线索吗?

【问题讨论】:

  • 您可以尝试动态 Linq 库,它是一个较旧的代码 plex 项目

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


【解决方案1】:

您可以在查询中包含参数检查

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多