본문 바로가기
카테고리 없음

🥰 c# dapper를 이용한 조건문 샘플

by Knowledge Store In Hyunsoft 2024. 9. 3.

 

 

 

  • c# dapper를 이용한 조건문 샘플
using System;
using System.Data.SqlClient;
using Dapper;
using System.Text;
using System.Collections.Generic;

public class UserRepository
{
    private readonly string _connectionString;

    public UserRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public IEnumerable<User> GetUsers(int? status = null, DateTime? createdAt = null, string email = null)
    {
        using (var connection = new SqlConnection(_connectionString))
        {
            var sql = new StringBuilder("SELECT id, name, email, created_at FROM users");
            var whereClauses = new List<string>();
            var parameters = new DynamicParameters();

            // 조건에 따른 동적 WHERE 절 생성
            if (status.HasValue)
            {
                whereClauses.Add("status = @Status");
                parameters.Add("Status", status.Value);
            }

            if (createdAt.HasValue)
            {
                whereClauses.Add("created_at > @CreatedAt");
                parameters.Add("CreatedAt", createdAt.Value);
            }

            if (!string.IsNullOrEmpty(email))
            {
                whereClauses.Add("email = @Email");
                parameters.Add("Email", email);
            }

            // WHERE 절이 존재하는 경우 추가
            if (whereClauses.Count > 0)
            {
                sql.Append(" WHERE ");
                sql.Append(string.Join(" AND ", whereClauses));
            }

            return connection.Query<User>(sql.ToString(), parameters);
        }
    }
}
728x90

댓글