[Dapper]スカラー値のクエリ

DataBaseは、SQL Serverで、データはAdventureWorks2022をいれています
→AdventureWorksについて

Count、Sum、Avg、Max、Minなどの1データ取得する場合に以下メソッドを使用します

  • ExecuteScalar
  • ExecuteScalarAsync

サンプル:

using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;

try
{
    var config = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile(@"appsettings.json")
                    .Build();

    var connectStr = config["ConnectionStrings:DefaultConnection"];

    using (var connection = new SqlConnection(connectStr))
    {
        connection.Open();

        var sql = "SELECT COUNT(*) FROM HumanResources.Employee";
        var count = connection.ExecuteScalar<int>(sql);
    }
}
catch(Exception ex)
{
    Console.Write(ex.ToString());
}
投稿日時: 2025-09-13 15:17:13
更新日時: 2025-09-13 18:02:13

内部リンク

Comment

最近の投稿

最近のコメント

タグ

アーカイブ

その他