简体   繁体   中英

How to use WILDCARD using Dapper

How can I use LIKE wildcard in postgre DB using Dapper? I have the following code:

string query = "SELECT name, index FROM article WHERE prefiks LIKE :prefix ;";
return conn.Query<myModel>(query , new { prefix = searchingValue }).ToArray();

Where searchingValue is a simple string. I tried few combinations which I already found:

return conn.Query<myModel>(query , new { prefix = "%" + searchingValue + "%" }).ToArray();

or

string query = "SELECT name, index FROM article WHERE prefix LIKE '%' || :prefix || '%'"
return conn.Query<myModel>(query , new { prefix = searchingValue }).ToArray();

But nothing works. I suppose that above solutions are fine for MS SQL but doesn't work under postgre;

Following should work:

string query = "SELECT name, index FROM article WHERE prefiks LIKE :prefix ;";
searchingValue = "%" + searchingValue + "%";
return conn.Query<myModel>(query , new { prefix = searchingValue }).ToArray();

or simply, combine the concatenation in one line:

return conn.Query<myModel>(query , new { prefix = "%" + searchingValue + "%" }).ToArray();

Alternatively, you may use string concatenation in SQL itself:

string query = "SELECT name, index FROM article WHERE prefiks LIKE CONCAT('%', :prefix, '%') ;";
return conn.Query<myModel>(query , new { prefix = searchingValue }).ToArray();

Note: I am not postgresql expert; so you may need to tune some syntax; just in case.

This question discusses about case sensitivity of postgresql; may be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM