转自:https://codedefault.com/2018/does-dapper-support-the-like-operator-in-csharp-application

问题描述

如题,在.NET/C#的程序开发中,使用Dapper查询数据时,如何实现类似SQL查询语句中的like操作,如:

var data = conn.Query(@"
    select top 25 
    Term as Label, 
    Type, 
    ID 
    from SearchTerms 
    WHERE Term like '%@T%'", 
    new { T = (string)term });

以上的语句执行后的结果是错误的,在Dapper中,类似SQL语句中的like应该如何处理呢?

方案一

term = "whateverterm";
var encodeForLike = term => term.Replace("[", "[[]").Replace("%", "[%]");

string term = "%" + encodeForLike(term) + "%";
var data = conn.Query(@"
   select top 25 
  Term as Label, 
  Type, 
  ID 
  from SearchTerms 
  WHERE Term like @term", 
  new { term });

方案二

string query = "SELECT * from country WHERE Name LIKE CONCAT('%',@name,'%');"
var results = connection.query<country>(query, new {name});

方案三

db.Query<Remitente>("SELECT * 
                     FROM Remitentes 
                     WHERE Nombre LIKE @n", new { n = "%" + nombre + "%" })
                   .ToList();

相关文章:

  • 2022-03-02
  • 2022-12-23
  • 2021-09-23
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-26
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-17
  • 2022-02-12
相关资源
相似解决方案