코드 3-1 추상화를 위반하여 기능 구현하기
public class UserStats { → 모델을 정의한다.
public int Received { get; set; }
public int Sent { get; set; }
}
public class StatsController: ControllerBase { → 컨트롤러
public UserStats Get(int userId) { → API 엔드포인트
var result = new UserStats();
string connectionString = config.GetConnectionString("DB");
using (var conn = new SqlConnection(connectionString)) {
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText =
"SELECT COUNT(*) FROM Messages WHERE FromId={0}";
cmd.Parameters.Add(userId);
result.Sent = (int)cmd.ExecuteScalar();
cmd.CommandText =
"SELECT COUNT(*) FROM Messages WHERE ToId={0}";
result.Received = (int)cmd.ExecuteScalar();
}
return result;
}
}