Dapper parameters in C#
Parameterized SQL from anonymous objects.
using Dapper;
using Microsoft.Data.Sqlite;
using var db = new SqliteConnection("Data Source=:memory:");
db.Execute("CREATE TABLE runs(lang TEXT, tpm INT)");
db.Execute("INSERT INTO runs VALUES ('csharp', 95), ('rust', 88)");
// anonymous objects carry parameters; Dapper handles the quoting
var fast = db.Query<int>(
"SELECT tpm FROM runs WHERE lang = @Lang AND tpm > @Floor",
new { Lang = "csharp", Floor = 90 });
Console.WriteLine(string.Join(",", fast));
Console.WriteLine(db.ExecuteScalar<long>("SELECT COUNT(*) FROM runs"));
How it works
@Langand@Floorbind from the object's property names.- Parameters mean quoting and injection are Dapper's problem.
ExecuteScalar<long>fetches a single value with its type.
Keywords and builtins used here
intlongnewstringusingvar
The run, in numbers
- Lines
- 14
- Characters to type
- 532
- Tokens
- 84
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 59 seconds.
Step 2 of 2 in Data with Dapper, step 5 of 16 in The open ecosystem.