Does a query return this?
var teste = _connection.Query(sQuery.ToString(), par).FirstOrDefault();
Well, inside the var test I have this:
UF = "MA"
But I just want the MA .
How do I get the dapper to return only the value?
Does a query return this?
var teste = _connection.Query(sQuery.ToString(), par).FirstOrDefault();
Well, inside the var test I have this:
UF = "MA"
But I just want the MA .
How do I get the dapper to return only the value?
In this case, the dapper should return you an object of type dynamic
.
Just do this:
var teste = _connection.Query(sQuery.ToString(), par).FirstOrDefault().UF;
Since type dynamic
is an implementation of Late Binding , it transfers the responsibility of knowing the content of the object to the programmer at run time. This is usually a 'two-legged knife' . While giving this kind of convenience, the code becomes fragile for maintenance and a small change in its sQuery
variable, for example, can cause problems.
In this type of situation, you can soften the negative effects of using dynamic by explicitly telling what you expect to return in your query.
Assuming your query looks like this:
string sQuery = "SELECT TOP 1 UF FROM TabelaCidade WHERE codigo = @Codigo";
You should be able to get the same result - and in a less fragile way - if you do Query
like this:
var teste = _connection.Query<string>(sQuery.ToString(), par).FirstOrDefault();
So you will know at compile time the type of variable teste
and is less susceptible to future errors.
With dapper you have several ways to do this, here are some 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 link site you will find more information.