Skip to content

Commit d32a3be

Browse files
committed
Merge pull request #31 from mgravell/dapper-use-QueryFirstOrDefault
Dapper: micro-optimizations
2 parents 53e386a + 78457f9 commit d32a3be

File tree

3 files changed

+6
-14
lines changed

3 files changed

+6
-14
lines changed

src/Benchmarks/FortunesDapperMiddleware.cs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,14 +46,13 @@ public async Task Invoke(HttpContext httpContext, HtmlEncoder htmlEncoder)
4646

4747
private static async Task<IEnumerable<Fortune>> LoadRows(string connectionString, DbProviderFactory dbProviderFactory)
4848
{
49-
var result = new List<Fortune>();
49+
List<Fortune> result;
5050

5151
using (var db = dbProviderFactory.CreateConnection())
5252
{
5353
db.ConnectionString = connectionString;
54-
await db.OpenAsync();
55-
56-
result.AddRange(await db.QueryAsync<Fortune>("SELECT [Id], [Message] FROM [Fortune]"));
54+
// note: don't need to open connection if only doing one thing; let dapper do it
55+
result = (await db.QueryAsync<Fortune>("SELECT [Id], [Message] FROM [Fortune]")).AsList();
5756
}
5857

5958
result.Add(new Fortune { Message = "Additional fortune added at request time." });

src/Benchmarks/MultipleQueriesDapperMiddleware.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,9 @@ private static async Task<World[]> LoadRows(int count, string connectionString,
8585

8686
for (int i = 0; i < count; i++)
8787
{
88-
var world = await db.QueryAsync<World>(
88+
result[i] = await db.QueryFirstOrDefaultAsync<World>(
8989
"SELECT [Id], [RandomNumber] FROM [World] WHERE [Id] = @Id",
9090
new { Id = _random.Next(1, 10001) });
91-
92-
result[i] = world.First();
9391
}
9492

9593
db.Close();

src/Benchmarks/SingleQueryDapperMiddleware.cs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,10 @@ private static async Task<World> LoadRow(string connectionString, DbProviderFact
6161
using (var db = dbProviderFactory.CreateConnection())
6262
{
6363
db.ConnectionString = connectionString;
64-
await db.OpenAsync();
65-
66-
var world = await db.QueryAsync<World>(
64+
// note: don't need to open connection if only doing one thing; let dapper do it
65+
return await db.QueryFirstOrDefaultAsync<World>(
6766
"SELECT [Id], [RandomNumber] FROM [World] WHERE [Id] = @Id",
6867
new { Id = _random.Next(1, 10001) });
69-
70-
db.Close();
71-
72-
return world.First();
7368
}
7469
}
7570
}

0 commit comments

Comments
 (0)