I am currently writing a method like this:
public async Task<UserModel> GetUserByUserIdAsync(string userId)
{
IQueryable<UserEntity> usersQuery = BuildQueryable(userId);
bool any = await usersQuery.ExecuteQuery().AnyAsync();
if (!any) return null; // wanna do other logic in the future
return (await usersQuery.ExecuteQuery().SingleAsync()).ToUserModel();
}
As you can see, I am calling the await usersQuery.ExecuteQuery()
twice, and ExecuteQuery()
is a method which iterates my database and could be considered an expensive operation. Is there any way I could save my IAsyncEnumerable<T>
like I normally would with IEnumerable<T>
and re-use it throughout my code?
I thought about using ToListAsync()
on it, but I am unsure whether that is considered good practice or not. I've also read that I could return a Task<IAsyncEnumerable<T>>
and do something with that maybe. What is the best way to handle this? I'd like to implement the most efficient solution.
>`, I could save the list in my other method, such as `var dbResponse = ExecuteQuery();` and then I could work with dbResponse throughout the method without making multiple trips to the database.
– Axajkamkat Jun 02 '21 at 12:54