使用带 ADO.NET 的 DbContext 的良好查询不返回任何结果
Good query returning no results using DbContext with ADO.NET
我需要 运行 在我的数据库上下文中进行以下查询。
SELECT u.[Email],
u.[EmailConfirmed],
u.[PhoneNumber],
STRING_AGG(r.[Name], ', ') AS Roles
FROM [AspNetUsers] u
LEFT OUTER JOIN [AspNetUserRoles] ur ON ur.UserId = u.Id
LEFT OUTER JOIN [AspNetRoles] r ON r.Id = ur.RoleId
GROUP BY u.[Email], u.[EmailConfirmed], u.[PhoneNumber]
当我在查询window中运行这个时,我得到了四个结果。所以我想出了下面的代码。
string UserQuery = @"SELECT u.[Email],
u.[EmailConfirmed],
u.[PhoneNumber],
STRING_AGG(r.[Name], ', ') AS Roles
FROM [AspNetUsers] u
LEFT OUTER JOIN [AspNetUserRoles] ur ON ur.UserId = u.Id
LEFT OUTER JOIN [AspNetRoles] r ON r.Id = ur.RoleId
GROUP BY u.[Email], u.[EmailConfirmed], u.[PhoneNumber]";
var conn = DbContext.Database.GetDbConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = UserQuery;
DbContext.Database.OpenConnection();
using var reader = cmd.ExecuteReader();
while (reader.NextResult())
{
Users.Add(new UserViewModel
{
Email = (string)reader["Email"],
EmailConfirmed = (bool)reader["EmailConfirmed"],
Phone = (string)reader["PhoneNumber"],
Role = (string)reader["Roles"]
});
}
这段代码运行s没有错误,但是第一次调用reader.NextResult()
returns false!
谁能看到我遗漏了什么?
应该是 reader.Read()
因为 reader.NextResult()
会返回下一个结果 set
参见:
Difference between SqlDataReader.Read and SqlDataReader.NextResult
我需要 运行 在我的数据库上下文中进行以下查询。
SELECT u.[Email],
u.[EmailConfirmed],
u.[PhoneNumber],
STRING_AGG(r.[Name], ', ') AS Roles
FROM [AspNetUsers] u
LEFT OUTER JOIN [AspNetUserRoles] ur ON ur.UserId = u.Id
LEFT OUTER JOIN [AspNetRoles] r ON r.Id = ur.RoleId
GROUP BY u.[Email], u.[EmailConfirmed], u.[PhoneNumber]
当我在查询window中运行这个时,我得到了四个结果。所以我想出了下面的代码。
string UserQuery = @"SELECT u.[Email],
u.[EmailConfirmed],
u.[PhoneNumber],
STRING_AGG(r.[Name], ', ') AS Roles
FROM [AspNetUsers] u
LEFT OUTER JOIN [AspNetUserRoles] ur ON ur.UserId = u.Id
LEFT OUTER JOIN [AspNetRoles] r ON r.Id = ur.RoleId
GROUP BY u.[Email], u.[EmailConfirmed], u.[PhoneNumber]";
var conn = DbContext.Database.GetDbConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = UserQuery;
DbContext.Database.OpenConnection();
using var reader = cmd.ExecuteReader();
while (reader.NextResult())
{
Users.Add(new UserViewModel
{
Email = (string)reader["Email"],
EmailConfirmed = (bool)reader["EmailConfirmed"],
Phone = (string)reader["PhoneNumber"],
Role = (string)reader["Roles"]
});
}
这段代码运行s没有错误,但是第一次调用reader.NextResult()
returns false!
谁能看到我遗漏了什么?
应该是 reader.Read()
因为 reader.NextResult()
会返回下一个结果 set
参见:
Difference between SqlDataReader.Read and SqlDataReader.NextResult