Dapper query and execute
Dapper query and execute
Dapper is a small object mapper built on ADO.NET connections. It runs SQL you supply and turns result columns into objects or scalar values. Use Query for several rows, QuerySingle for exactly one, and Execute for commands that change data. The provider still owns connections, transactions and database-specific behavior.
Proposed baseline: .NET 10 / C# 14 (SDK 10.0.404 inherited). Private SQLite in-memory fixture, Dapper 2.1.100 or EF Core SQLite 10.0.15 candidate dependencies. Approve dependencies before restore; no external database needed. Outputs are reasoned, not executed.
Read a list of book titles
Open a private SQLite connection and create a two-row fixture. Order by ID so the display is predictable.
using System;using System.Linq;using Dapper;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();db.Execute("CREATE TABLE Books (Id INTEGER PRIMARY KEY, Title TEXT NOT NULL, Stock INTEGER NOT NULL CHECK(Stock >= 0))");db.Execute("INSERT INTO Books VALUES (1, 'Atlas', 4), (2, 'Notebook', 1)");foreach (var title in db.Query<string>("SELECT Title FROM Books ORDER BY Id")) Console.WriteLine(title);Query<string> reads a single column from every row. The default buffered query collects the results before returning.
Expected observation (reasoned, not executed):
AtlasNotebookUpdate only an eligible row
Bind the identifier and requested amount. The predicate prevents inventory from going below zero.
using System;using System.Linq;using Dapper;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();db.Execute("CREATE TABLE Books (Id INTEGER PRIMARY KEY, Title TEXT NOT NULL, Stock INTEGER NOT NULL CHECK(Stock >= 0))");db.Execute("INSERT INTO Books VALUES (1, 'Atlas', 4), (2, 'Notebook', 1)");const string sql = "UPDATE Books SET Stock = Stock - @Amount WHERE Id = @Id AND Stock >= @Amount";Console.WriteLine(db.Execute(sql, new { Id = 1, Amount = 2 }));Console.WriteLine(db.Execute(sql, new { Id = 2, Amount = 2 }));Console.WriteLine(db.QuerySingle<int>("SELECT Stock FROM Books WHERE Id = 1"));The first update changes one row, the second changes none. Zero affected rows can mean either a missing ID or insufficient stock; this statement does not distinguish them.
Expected observation (reasoned, not executed):
102Roll back two related changes
Use the same explicit transaction for both commands, then roll back to demonstrate that neither survives.
using System;using System.Linq;using Dapper;using Microsoft.Data.Sqlite;using var db = new SqliteConnection("Data Source=:memory:;Pooling=False");db.Open();db.Execute("CREATE TABLE Books (Id INTEGER PRIMARY KEY, Title TEXT NOT NULL, Stock INTEGER NOT NULL CHECK(Stock >= 0))");db.Execute("INSERT INTO Books VALUES (1, 'Atlas', 4), (2, 'Notebook', 1)");using (var tx = db.BeginTransaction()){ db.Execute("UPDATE Books SET Stock = Stock - 1 WHERE Id = 1", transaction: tx); db.Execute("UPDATE Books SET Stock = Stock + 1 WHERE Id = 2", transaction: tx); tx.Rollback();}Console.WriteLine(string.Join(",", db.Query<int>("SELECT Stock FROM Books ORDER BY Id")));Both statements are enlisted in the same transaction. The query after rollback observes the original values.
Expected observation (reasoned, not executed):
4,1Common mistakes and edge cases
Execute does not return the inserted primary key. Use a provider-supported returning clause or a separate correctly scoped key retrieval strategy. Never assume row counts are identical across engines and command types. Validate that an amount is positive before issuing the guarded update. For unbuffered queries keep the connection alive until enumeration ends or the enumerator is disposed. A buffered result can outlive the reader but buffering consumes memory proportional to the result. When several commands belong to one transaction, pass that transaction explicitly to each Dapper call; executing a sequence of calls does not by itself create an atomic unit. Microsoft.Data.Sqlite async methods do not provide true asynchronous database I/O.
Practice and recap
Write a guarded update for buying one Notebook, then buying another. Record affected-row counts and final stock; explain why the second purchase fails.
Hint: Reuse the stock predicate.
Learning objective: Select mapped rows versus affected-row counts. See accompanying manual practice and knowledge check.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dapper query and execute — knowledge check
Apply the lesson concepts to the following scenarios.
Which method returns many mapped values?
What does a zero guarded update tell you?
What fixes row display order?
How do two commands join a local transaction?
What owns SQL dialect semantics?