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

Asked

Viewed 220 times

4

I’m using the Dapper that has the purpose of map properties of objects.

See a practical example:

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

That is, the object Servico will have all its properties mapped according to the table Servico 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 be clarified.


Doubt

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

Illustration example:

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
Cannot implicitly Convert type 'System.Collections.Generic.Ienumerable' to 'string'

2 answers

3

An alternative to getting only one field in an SQL query using Dapper is to specify its type, 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, but with the method FirstOrDefault() only one is obtained string which is the first item on the list, and it is left to the discretion to deal with the exception ArgumentNullException his.

Source:
https://msdn.microsoft.com/pt-br/library/bb340482(v=vs.110). aspx
https://github.com/StackExchange/dapper-dot-net

  • Gabe banned me from chat. I have no way to respond there. Please add me on Facebook.

3


You’re trying to play the result of a query which 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 obviously is the field, and [0] is picking up 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 put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.