Question

There is signature of UserManager method (ASP .NET Identity Core default implementation):

public Task<IList<string>> GetRolesAsync(User user) {
    const string query = @"
                select r.[Name]
                  from [UserRoles] ur
             left join [Roles] r on r.RoleId = ur.RoleId
                 where ur.UserId = @userId;
    ";

    return Task.Factory.StartNew(() => {
        using (SqlConnection connection = new SqlConnection(_connectionString))
            return connection.Query<string>(query, new { userId = user.UserId });
    });
}

But unfortunately Dapper.Query<T> returns IEnumerable<T>.

Is it possible to return IList<T> or i have to make conversion myself?

Was it helpful?

Solution 3

Try to use an explicit cast

return (IList<string>)connection.Query<string>(query, new { userId = user.UserId });

OTHER TIPS

Dapper only guarantees to hand you an IEnumerable<T>. So you should only assume that. In particular, it already has different scenarios where it can give you either a populated list, or a deferred iterator.

The simplest approach is to just call .ToList(). If you are intent on avoiding an alloc, then maybe do a speculative test:

static IList<T> SpeculativeToList<T>(this IEnumerable<T> source)
{
    return source as IList<T> ?? source.ToList();
}

Just call .ToList() on it?

return connection.Query<string>(query, new { userId = user.UserId }).ToList();

This would enumerate the IEnumerable<T> and create an in-memory copy of all elements found as a List<T>.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top