首页 > 解决方案 > 如何在 EF 6 中使用原始 sql 查询循环遍历行?

问题描述

如何从下面的查询中获取值并循环它们?查询返回一个计数。

var quantities = db.Database.SqlQuery<List<string>>
        (@"SELECT  Quantity
        FROM   Runlist WHERE(UserId = @userid) 
        GROUP BY Quantity", new SqlParameter("@userid", user.Id)).ToList();

foreach (var qty in quantities)
{

}

这是查询的结果。

Quantity
---------
1250
1750
2500
5000
5250
6250
11500
12250
12500
15500
17000
164250

在此处输入图像描述

标签: c#sqlentity-framework

解决方案


像这样替换您的查询以获得数量的计数

List<string> quantities = new List<string>();
quantities = db.Database.SqlQuery<List<string>>
        (@"SELECT Quantity 
        FROM   Runlist WHERE(UserId = @userid) 
        GROUP BY Quantity", new SqlParameter("@userid", user.Id)).ToList();

foreach (var qty in quantities)
{
 // get value here

}

推荐阅读