How to map and get only one property or field of a query?

4

I'm using Dapper to map object properties .

See a practical example:

var servico = conexao.Query<Servico>(statement.ToSql(), new { IdServico = id }).First();

That is, the Servico object will have all its properties mapped according to the Servico table of the database and the data will be populated in the object at runtime.

However, I have a question regarding property mapping, which I would like to see clarified.

Doubt

I would like to know if it is possible to map and get only one property or field of an SQL query using Dapper? And the field to be obtained would be the Descricao field as follows in the illustration example.

Example illustration illustration:

using (conexao = new SQLiteConnection(StringDeConexao))
{
    conexao.Open();

    var sql = "select s.Descricao from Servico s where s.Descricao = @Descricao";

    string campoDescricao = conexao.Query(sql, new { Descricao = "Descricao de teste" });    
}

The above attempt results in the following error:

  

Error CS0029
  Can not implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string'

    
asked by anonymous 29.01.2017 / 16:07

2 answers

3

You are trying to play the result of a query that is a collection in a string , this does not work and is not what you want. Take the result, then take the desired field:

using (conexao = new SQLiteConnection(StringDeConexao)) {
    conexao.Open();
    var resultado = conexao.Query("select s.Descricao from Servico s where s.Descricao = @Descricao", new { Descricao = "Descricao de teste" });
    var campoDescricao = resultado[0].Descricao;
}

Descricao is obviously the field, and [0] is catching the first line of the generated collection. If you have the possibility of having more than one line, you would need to make a loop.

I've placed it on GitHub for future reference .

    
29.01.2017 / 16:14
3

An alternative to get only one field in a SQL query using Dapper is to specify the type of it, see an example:

using (conexao = new SQLiteConnection(StringConexao))
{
    conexao.Open();

    var sql = "select nome from pessoa where id = @id";

    var nome = conexao.Query<string>(sql, new { id = meuId }).FirstOrDefault();

    Writeline($"Nome: {nome}");
}

The return will be an enumerated list IEnumerable<string> type string , however, with the FirstOrDefault() method you get only a string which is the first element in the list, ArgumentNullException of it.

Source:
link
< a href="https://github.com/StackExchange/dapper-dot-net"> link

    
01.02.2017 / 02:53