如何将我的dapper结果转换为List?

16

为什么我不能在这里添加.ToList()?唯一允许的是.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;
}
//..

更新

我认为问题与conn.queryasync有关(conn是context.Database.Connection.ConnectionString),而不是context.Database.SqlQuery。


3
如果我没记错的话,通用参数应该是 ProfitMargin,而不是 List<ProfitMargin> - user47589
你需要添加 "using System.Linq" 才能让智能感知显示 Linq 扩展方法,例如 ToList()。 - Joe
你试图调用ToList()函数的对象是什么? - DespeiL
2个回答

26

试着改成这样。

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

或者

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

我认为你试图调用 .ToList() 函数来操作 Task 对象。


为什么我不能使用.tolistasync?- .tolist现在可以工作了。 - DinaDee
1
.QueryAsync<t> 返回的是 Task<t> 对象而非 t 对象。Task 对象有其自己的属性等,其中之一是 Result,当执行完成时,它会保存您的 IEnumerable<ProfitMargin> 对象。基本上,您会尝试在没有定义 .ToList() 函数的 Task 上调用 .ToList()await 与括号交互有点奇怪。把 await 看作一个转换,要对所转换的对象进行操作,您必须将整个内容用括号括起来。 - Matti Price
1
QueryAsync 返回一个类型序列,根据上面的答案,响应类型应该是 IEnumerable<IList<ProfileMargin>> 而不是 List<ProfileMargin>解决方案:如下所述,List<ProfitMargin> res = await conn.QueryAsync<ProfitMargin>(sqlQuery, new { QuoteId = QuoteIds.ToArray()})).ToList() - Raghav
need Dapper QueryToListAsync<t> - mathewsun

1

尝试:

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

或者

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

正如 @Amy 所说,你需要使用


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

该方法返回一个Task<IEnumerable<ProfitMargin>>,因此在等待后会评估为一个IEnumerable<ProfitMargin>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接