11

I want to perform the following query using Dapper, which currently doesn't return expected results (I think it must be treating the @pName param as literal text within the single quotes?):

var q = "SELECT * FROM Users WHERE Name LIKE '@pName%'";

@pName is the param I assign a value to upon executing the query.

Things work if I just build the SQL like:

var q = "SELECT * FROM Users WHERE Name LIKE '" + name + "%'";

.. but I would prefer to use a param if possible.

I am executing the query using the following code:

o = _cn.Query<User>(q, new { pName = new DbString { Value = name, IsFixedLength = false, Length = 25, IsAnsi = true } }).ToList();

How do I got about this using Dapper?

marcusstarnes
  • 6,393
  • 14
  • 65
  • 112

2 Answers2

18
SELECT * FROM Users WHERE Name LIKE @pName + '%'
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
1

I would like to add here another possible solution:

var results = cn.Query("SELECT * FROM Table WHERE Column LIKE @value", new { value = value + "%" });

The wildcard is inside the string var itself, and then we reference that var in the SQL. Applies to any wildcard pattern you want.

Diego Senra
  • 61
  • 1
  • 6