2
A query returns this?
var teste = _connection.Query(sQuery.ToString(), par).FirstOrDefault();
well, within the var test I have it:
UF = "MA"
but I just want the MA.
How do I make Dapper return me only the value?
2
A query returns this?
var teste = _connection.Query(sQuery.ToString(), par).FirstOrDefault();
well, within the var test I have it:
UF = "MA"
but I just want the MA.
How do I make Dapper return me only the value?
4
In this case, Dapper should return an object of the type dynamic
.
Just do it like this:
var teste = _connection.Query(sQuery.ToString(), par).FirstOrDefault().UF;
Like the guy dynamic
is an implementation of Late Binding, it transfers the responsibility of knowing the content of the object to the programmer at runtime. This is usually a 'double vegetable knife'. At the same time that it gives this type of convenience, the code is fragile for maintenance and a small change in its variable sQuery
, for example, can cause problems.
In this type of situation, you can mitigate the negative effects of using Dynamic by explaining what you expect as a return already in your query.
Suppose your query is like this:
string sQuery = "SELECT TOP 1 UF FROM TabelaCidade WHERE codigo = @Codigo";
You should be able to receive the same result - and in a less fragile way - if you do the Query
that way:
var teste = _connection.Query<string>(sQuery.ToString(), par).FirstOrDefault();
Thus, you will know at compile time the variable type teste
and is less susceptible to future errors.
3
With Dapper you have several ways to do this, below are examples:
//Aqui você está tipando o retorno em string e já pegando o primeiro resultado
var uf = _connection.QueryFirstOrDefault<string>(sQuery.ToString(), parm);
//Aqui você converte o retorno no seu model, e posteriormente poderá pegar seuModel.UF (onde uf é a propriedade)
var teste = _connection.Query<SeuModel>(sQuery.ToString(), par).FirstOrDefault();
var uf = teste.UF;
On the website http://dapper-tutorial.net/dapper you can find more information.
Browser other questions tagged c# dapper
You are not signed in. Login or sign up in order to post.
He’s a little confused, give more details, what query he’s getting?
– Vinícius Lima
@Viníciuslima, how I only get the value of Dapper
– pnet
The Dapper should return you one
dynamic
in that case. Just dovar teste = _connection.Query(sQuery.ToString(), par).FirstOrDefault().UF;
– Diego Rafael Souza
@Diegorafaelsouza, put as an answer, I mark her.
– pnet