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
?
To use Dapper, we first need a DbConnection implementation. In this example, we'll be using System. Data. SqlClient and SqlConnection , but Dapper supports other databases that use the DbConnection abstraction.
The value of the parameter is used along with LIKE operator (statement) in a SELECT statement. In the above Stored Procedure, the LIKE operator (statement) works as CONTAINS where it looks for the match throughout the string value. You can also use it as STARTS WITH and ENDS WITH options as shown below.
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.
The DynamicParameters type provides an Add method, enabling you to pass explicit parameters, specifying the datatype, direction and size: var parameters = new DynamicParameters(); var customerId = "ALFKI"; parameters. Add("@CustomerId", customerId, DbType.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With