Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Dapper support the like operator?

Tags:

sql

dapper

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?

like image 314
Jay Stevens Avatar asked May 17 '11 11:05

Jay Stevens


People also ask

Does dapper use SqlClient?

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.

How can we use like operator in stored procedure in SQL Server?

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.

What is the LIKE operator used for?

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.

What is DynamicParameters in dapper C#?

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.


1 Answers

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.

like image 111
Sam Saffron Avatar answered Oct 11 '22 14:10

Sam Saffron