Crizy Sash
Crizy Sash

Reputation: 127

How to convert the following method to asynchronous method?

I need to convert this method to asynchronous method.

public User GetUserByID(int id)
 {
    return  _unitofwork.UserRepository.FindByCondition(u => u.Id == id).FirstOrDefault();
 }

This is how I change the code.

public async Task<User> GetUserByID(int id)
 {
    return await _unitofwork.UserRepository.FindByCondition(u => u.Id == id).FirstOrDefault();
 }

but .FirstOrDefault() or .FirstOrDefaultAsync() cannot use there.I only need to return single user. Can anyone point me to right direction?

'Task<IEnumerable<User>>' does not contain a definition for 'FirstOrDefault' and no accessible extension method 'FirstOrDefault' accepting a first argument of type 'Task<IEnumerable<User>>' could be found (are you missing a using directive or an assembly reference?) [JobsPortal]

Edit- Sorry. My bad, minor mistake. I should have use code like this.

public async Task<User> GetUserByID(int id)
 {
    return (await _unitofwork.UserRepository.FindByCondition(u => u.Id == id)).FirstOrDefault();
 }

Upvotes: 0

Views: 273

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40988

It seems like FindByCondition is an asynchronous method itself.

You just need some extra brackets in there so you await the result from FindByCondition before you call FirstOrDefault() on it.

return (await _unitofwork.UserRepository.FindByCondition(u => u.Id == id)).FirstOrDefault();

The way you had it, it was trying to call FirstOrDefault on the Task returned from FindByCondition without awaiting it.

Upvotes: 4

Related Questions