我编写了以下用于从SQL Server数据库中读取数据的代码,但它引发了一个异常:
在阅读器关闭时无效尝试呼叫
ReadAsync()
。
我调试了我的代码。备注内联代码。
[HttpGet]
public async Task<ActionResult> Index()
{
List<Categorie> hfds = new List<Categorie>();
try
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
using (SqlCommand comm = new SqlCommand("SELECT id, naam, beschrijving from categorie", conn))
{
await conn.OpenAsync(); // connection string is ok
using (DbDataReader reader = await comm.ExecuteReaderAsync())
{
while (await reader.ReadAsync()) // on this line give compiler a
// exception when he comes to the
// line for the second time.
{
int id = (int)reader["ID"];
Categorie c = new Categorie()
{
Naam = reader["naam"].ToString(),
ID = id,
Beschrijving = reader["beschrijving"].ToString()
};
c.TopVijf = await TopicController.GeefTopVijfTopicsVanCategorie(id, conn);
hfds.Add(c);
// after one time running the loop is everyting alright.
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Er is een exception geworpen: {ex.Message}!", "Exception");
return View(new HomeViewModel());
}
return View(new HomeViewModel() { Categorieen = hfds });
}
public static async Task<List<Topic>> GeefTopVijfTopicsVanCategorie(int catId, SqlConnection conn)
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
using (SqlCommand comm = new SqlCommand("declare @catid int = @id; declare @aantal int = (select top 1 MinTwee + MinEen + nul + PlusEen + PlusTwee from topic where categorieID = @catid and verwijderd = 0); if (@aantal = 0) set @aantal = 1; select top 5 id, mintwee, mineen, nul, pluseen, plustwee, naam from topic where CategorieID = @catid and verwijderd = 0 order by round(cast((mintwee * (-2) + mineen * (-1) + nul * 0 + pluseen * 1 + PlusTwee * 2) as float) / @aantal, 1) desc, creatie desc", conn))
{
comm.Parameters.Add(new SqlParameter("@id", catId) { SqlDbType = SqlDbType.Int });
await conn.OpenAsync();
List<Topic> topics = new List<Topic>();
using (DbDataReader reader = await comm.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
topics.Add(new Topic()
{
ID = (int)reader["id"],
Naam = reader["naam"].ToString(),
MinTwee = (int)reader["mintwee"],
MinEen = (int)reader["mineen"],
Nul = (int)reader["nul"],
PlusEen = (int)reader["PlusEen"],
PlusTwee = (int)reader["PlusTwee"]
});
}
reader.Close();
}
return topics;
// also here must be everything good.
}
}
另请参见两个DbDataReaders
合二为一。我认为这是我的问题,但我不知道如何解决它。你能救我吗?
答案 0 :(得分:0)
我找到了!我已将此代码放在网站的第一个SqlCommand
。
c.TopVijf = await TopicController.GeefTopVijfTopicsVanCategorie(id, conn);