-1

I need to run the following query on my DB context.

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]

When I run this in the query window, I get four results. So I came up with the following code.

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"]
    });
}

This code runs without error, but the first call to reader.NextResult() returns false!

Can anyone see what I'm missing?

3
  • Is your context pointing at the same DB? Commented Jun 22, 2020 at 21:27
  • You mean the same DB where the query worked? Yes, definitely. And the four results confirm that is the DB I'm working with. Commented Jun 22, 2020 at 21:28
  • It may be that the string is not properly escaped. Could you try this: pastebin.com/Z7KAY9mN Commented Jun 22, 2020 at 21:44

1 Answer 1

1

Should be reader.Read() as reader.NextResult() will bring back the next result set

See:

Difference between SqlDataReader.Read and SqlDataReader.NextResult

Sign up to request clarification or add additional context in comments.

1 Comment

Well don't I feel stupid. Guess I haven't worked with raw ADO.NET in a while.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.