2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[C#][Dapper]DapperでSUMを実行する

Last updated at Posted at 2018-05-23

Dapper(C#のMicroOrm)でSUMを実行する方法です。

/// <summary>
/// ユーザーのバトルの合計スコアを取得する
/// </summary>
/// <returns>スコア</returns>
public uint SumBattleScore(ulong userId)
{
    IDbConnection conn = /* 何かしらの方法で取得する */;
    string sql = "SELECT SUM(score) FROM battle_result WHERE user_id = @UserId";

    return Convert.ToUInt32(conn.ExecuteScalar(sql, new { UserId = userId }));

    // ExecuteScalar が使えることを教えてもらいました
    /*
    uint? data = conn.QueryFirst<uint?>(sql, new { UserId = userId });
    return (data == null) ? 0 : data.Value;
    */
}

データが何も取得できないときはNullになるみたいなので、Nullable型で取得してあげる必要あるみたい。

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?