I'm trying to map a many to many relationship into a User with a list of Roles
I tried doing as this question Dapper Many-to-Many Query but it gave me multiple users with a single role each.
Instead I'm trying to use the QueryMultiple statement. My issue here is that I'm querying the user from an Email but need to query the Role from the user's Id. So I need to access the result of the first query statement to pass in the Id to the second. How can I do this?
public async Task<User> GetUserByEmailAsync(string email, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
using (var connection = new SqlConnection(_options.ConnectionString))
{
await connection.OpenAsync(cancellationToken);
var results = await connection.QueryMultipleAsync(@"SELECT * FROM [User] WHERE Email = @email; " +
"SELECT Id, Name, NormalizedName FROM [Role] JOIN [UserRole] ON [Role].Id = UserRole.RoleId" +
" WHERE [UserRole].UserId = 2", // <-- NEED TO INSERT USER ID DYNAMICALLY HERE
new
{
email
});
var user = await results.ReadSingleAsync<User>();
var roles = await results.ReadAsync<Role>();
foreach (var role in roles)
{
user.Roles.Add(role);
}
return user;
}
}