Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get my dapper result to be a List?

Tags:

c#

dapper

Why I can't add a .ToList() on this? The only thing Intellisense is allowing is .ToString().

//..
string sqlQuery = "SELECT sum(SellingPrice) as SellingPrice, sum(MarkupPercent) as MarkupPercent, sum(MarkupAmount) as MarkupAmount FROM ProfitMargins WHERE QuoteId in @QuoteId group by multiplier";
{
    List<ProfitMargin> profitMargin = (List<ProfitMargin>)await conn.QueryAsync<List<ProfitMargin>>(sqlQuery, new { QuoteId = QuoteIds.ToArray()})  //would like to add .ToList() here;

    return profitMargin;
}
//..

UPDATE

I believe the problem has to do with conn.queryasync (conn is context.Database.Connection.ConnectionString) instead of context.Database.SqlQuery

like image 566
DinaDee Avatar asked Sep 20 '16 18:09

DinaDee


People also ask

What is QueryAsync in dapper?

QueryAsync. This method gets a list of query results that can be enumerated.

What is splitOn in Dapper?

splitOn: CustomerId will result in a null customer name. If you specify CustomerId,CustomerName as split points, dapper assumes you are trying to split up the result set into 3 objects. First starts at the beginning, second starts at CustomerId , third at CustomerName . Follow this answer to receive notifications.

How does Dapper mapping work?

Dapper maps data to the first type in the same way as it does if only one generic parameter has been supplied to the QueryAsync<T> method. If is then told to map data to the Category type, and to assign the resulting object to the product's Category property.


2 Answers

Try changing to this.

List<ProfitMargin> profitMargin = (await conn.QueryAsync<ProfitMargin>(sqlQuery, new { QuoteId = QuoteIds.ToArray()})).ToList();

Or

var results = await conn.QueryAsync<ProfitMargin>(sqlQuery, new { QuoteId = QuoteIds.ToArray()});
List<ProfitMargin> profitMargin = results.ToList();

I think you are hitting the Task object with your attempts at calling .ToList()

like image 133
Matti Price Avatar answered Oct 11 '22 16:10

Matti Price


Try:

List<ProfitMargin> profitMargin = new List<ProfitMargin>(await conn.QueryAsync<ProfitMargin>(sqlQuery, new { QuoteId = QuoteIds.ToArray()}));

or

List<ProfitMargin> profitMargin = (await conn.QueryAsync<ProfitMargin>(sqlQuery, new { QuoteId = QuoteIds.ToArray()})).ToList();

As @Amy stated, you need to use

conn.QueryAsync<ProfitMargin>(sqlQuery, new { QuoteId = QuoteIds.ToArray()}))

which returns a Task<IEnumerable<ProfitMargin>> thus upon awaiting evaluates to an IEnumerable<ProfitMargin>.

like image 20
Nick Avatar answered Oct 11 '22 17:10

Nick