Dapper 支持 like 运算符吗?

发布于 2024-11-08 06:39:48 字数 524 浏览 1 评论 0原文

使用 Dapper-dot-net...

以下内容不会在数据对象中产生任何结果:

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

但是,当我仅使用常规字符串格式时,例如:

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

我在集合中返回了 25 行。 Dapper 是否没有正确解析参数 @T 的末尾?

Using Dapper-dot-net...

The following yields no results in the data object:

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

However, when I just use a regular String Format like:

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

I get 25 rows back in the collection. Is Dapper not correctly parsing the end of the parameter @T?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

海拔太高太耀眼 2024-11-15 06:39:48

尝试:

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 });

like 运算符没有什么特别的,你永远不希望你的参数位于字符串文字中,它们不会工作,而是会被解释为字符串。

注意

强烈建议不要使用第二个代码片段中的硬编码示例,它除了是 sql 注入的一个大问题之外,还可能导致 dapper 泄漏。

警告

任何以通配符开头的like匹配都不可SARGable,这意味着它很慢并且需要索引扫描。

Try:

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 });

There is nothing special about like operators, you never want your params inside string literals, they will not work, instead they will be interpreted as a string.

note

The hard-coded example in your second snippet is strongly discouraged, besides being a huge problem with sql injection, it can cause dapper to leak.

caveat

Any like match that is leading with a wildcard is not SARGable, which means it is slow and will require an index scan.

花心好男孩 2024-11-15 06:39:48

是的,确实如此。这个简单的解决方案每次都对我有用:

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

Yes it does. This simple solution has worked for me everytime:

db.Query<Remitente>("SELECT * 
                     FROM Remitentes 
                     WHERE Nombre LIKE @n", new { n = "%" + nombre + "%" })
                   .ToList();
掌心的温暖 2024-11-15 06:39:48

使用它在查询中添加 concat 函数的最佳方法,因为它也可以节省 sql 注入,但 concat 函数仅支持高于 sql 2012

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

Best way to use this to add concat function in query as it save in sql injecting as well, but concat function is only support above than sql 2012

string query = "SELECT * from country WHERE Name LIKE CONCAT('%',@name,'%');"
var results = connection.query<country>(query, new {name});
围归者 2024-11-15 06:39:48

Sam 的答案对我不起作用,所以经过一些测试后,我想出了使用 SQLite CONCAT 等效项 似乎有效:

string sql = "SELECT * FROM myTable WHERE Name LIKE '%' || @NAME || '%'";
var data = IEnumerable data = conn.Query(sql, new { NAME = Name });

The answer from Sam wasn't working for me so after some testing I came up with using the SQLite CONCAT equivalent which seems to work:

string sql = "SELECT * FROM myTable WHERE Name LIKE '%' || @NAME || '%'";
var data = IEnumerable data = conn.Query(sql, new { NAME = Name });
尝蛊 2024-11-15 06:39:48

只是为了偏离 Sam 的答案,以下是我如何创建两个辅助方法,以便使用 LIKE 运算符使搜索变得更容易。

首先,创建一个用于生成参数化查询的方法,该方法使用 dynamic: ,但是在许多需要静态类型而不是动态类型的情况下,创建强类型泛型方法应该是更理想的。

public static dynamic ParameterizedQuery(this IDbConnection connection, string sql, Dictionary<string, object> parametersDictionary)
{
    if (string.IsNullOrEmpty(sql))
    {
        return null;
    }
    string missingParameters = string.Empty;
    foreach (var item in parametersDictionary)
    {
        if (!sql.Contains(item.Key))
        {
            missingParameters += $"Missing parameter: {item.Key}";
        }
    }
    if (!string.IsNullOrEmpty(missingParameters))
    {
        throw new ArgumentException($"Parameterized query failed. {missingParameters}");
    }
    var parameters = new DynamicParameters(parametersDictionary);
    return connection.Query(sql, parameters);
}

然后添加一个方法来创建可与 Dapper 配合使用的 Like 搜索词。

public static string Like(string searchTerm)
{
    if (string.IsNullOrEmpty(searchTerm))
    {
        return null;
    }
    Func<string, string> encodeForLike = searchTerm => searchTerm.Replace("[", "[[]").Replace("%", "[%]");
    return $"%{encodeForLike(searchTerm)}%";
}

用法示例:

var sql = $"select * from products where ProductName like @ProdName";
var herringsInNorthwindDb = connection.ParameterizedQuery(sql, new Dictionary<string, object> { { "@ProdName", Like("sild") } });

foreach (var herring in herringsInNorthwindDb)
{
    Console.WriteLine($"{herring.ProductName}");
}

我们从 Northwind DB 获取样本数据:
示例数据

我喜欢这种方法,因为我们使用辅助扩展方法来完成重复性工作。

Just to digress on Sam's answer, here is how I created two helper methods to make searches a bit easier using the LIKE operator.

First, creating a method for generating a parameterized query, this method uses dynamic: , but creating a strongly typed generic method should be more desired in many cases where you want static typing instead of dynamic.

public static dynamic ParameterizedQuery(this IDbConnection connection, string sql, Dictionary<string, object> parametersDictionary)
{
    if (string.IsNullOrEmpty(sql))
    {
        return null;
    }
    string missingParameters = string.Empty;
    foreach (var item in parametersDictionary)
    {
        if (!sql.Contains(item.Key))
        {
            missingParameters += 
quot;Missing parameter: {item.Key}";
        }
    }
    if (!string.IsNullOrEmpty(missingParameters))
    {
        throw new ArgumentException(
quot;Parameterized query failed. {missingParameters}");
    }
    var parameters = new DynamicParameters(parametersDictionary);
    return connection.Query(sql, parameters);
}

Then adding a method to create a Like search term that will work with Dapper.

public static string Like(string searchTerm)
{
    if (string.IsNullOrEmpty(searchTerm))
    {
        return null;
    }
    Func<string, string> encodeForLike = searchTerm => searchTerm.Replace("[", "[[]").Replace("%", "[%]");
    return 
quot;%{encodeForLike(searchTerm)}%";
}

Example usage:

var sql = 
quot;select * from products where ProductName like @ProdName";
var herringsInNorthwindDb = connection.ParameterizedQuery(sql, new Dictionary<string, object> { { "@ProdName", Like("sild") } });

foreach (var herring in herringsInNorthwindDb)
{
    Console.WriteLine(
quot;{herring.ProductName}");
}

And we get our sample data from Northwind DB:
Sample data

I like this approach, since we get helper extension methods to do repetitive work.

甜心小果奶 2024-11-15 06:39:48

我对这个问题的解决方案很简单:

parameter.Add("@nomeCliente", dfNomeCliPesquisa.Text.ToUpper());

query = "SELECT * FROM cadastrocliente WHERE upper(nome) LIKE " + "'%" + dfNomeCliPesquisa.Text.ToUpper() + "%'"; 

My solution simple to this problem :

parameter.Add("@nomeCliente", dfNomeCliPesquisa.Text.ToUpper());

query = "SELECT * FROM cadastrocliente WHERE upper(nome) LIKE " + "'%" + dfNomeCliPesquisa.Text.ToUpper() + "%'"; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文