Search code examples
c#sql-serverdapper

How to retrieve data from Dapper ExecuteReader() and convert it into an int


I'm using Dapper and I want to get all values from a column with a specific condition then convert it to a integer, but I'm unable to access those values.

| NumAdultos | NumCrianças |     
|     1      |     0       |    <-----------
|     2      |     1       |    <----------- I want to get all these values;
|     1      |     0       |    <-----------

Code:

int clienteAlojadoNum = 0;

using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.ConnectionString("Hotel")))
{
    // How do I convert this value?
    var adultos = connection.ExecuteReader($"SELECT NumAdultos, NumCrianças FROM dbo.Registos WHERE DataEntrada = @DataEntrada and Estado = 'Alojado' ", new { DataEntrada = hoje });

    // I know this is wrong but I don't how to access them or convert them
    clienteAlojadoNum = Convert.ToInt32(adultos);
}

Solution

  • public class Data {
     public int NumAdultos { get; set; }
     public int NumCrianças {get; set; }
    }
    
    int clienteAlojadoNum = 0;
    using(IDbConnection connection = new SqlConnection(Helper.ConnectionString("Hotel"))) {
    
      var results = connection.Query<Data>($"SELECT NumAdultos, NumCrianças FROM dbo.Registos WHERE DataEntrada = @DataEntrada and Estado = @Estado", new {
        DataEntrada = hoje, 
        Estado = "Alojado"
      });
    
      clienteAlojadoNum = results.Select(r => r.NumAdultos + r.NumCrianças).Sum();
    
    }