-1

I created this function and I am not sure that it is the best way to create an asynchronous function that gets data from entity framework:

public async Task<Employe?> EmployeToConnect(string login, string password)
    {
        Employe? employeResult = null;
        employeResult = await _context.Employes.FirstOrDefaultAsync
         (empl => empl.Login == login && empl.Password == password);
        return employeResult;
    }

Is there a better way to do it? (Seeing that the inspected returned type is Task< Employe> and we just returned Employe? )

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
  • It seems an opinion-based question, but if you want to learn about `?` you can check https://stackoverflow.com/a/28352116/6691714 – Reza Heidari Apr 16 '22 at 10:36
  • More than anything else your question is [How and when to use ‘async’ and ‘await’](https://stackoverflow.com/q/14455293/861716). – Gert Arnold Apr 16 '22 at 10:43

1 Answers1

0

The return type will still be a Task<Employee?>. Due to the async keyword the result of EmployeToConnect will be wrapped in a task. You could also avoid the async keyword and return the task directly, but this will affect how the exception handling works (although it would mean a very minor performance benefit).

  • Due to the async keyword, the result of EmployeToConnect will be wrapped into its own new task, which in turn awaits the underlying task from FirstOrDefaultAsync
  • Without the async keyword, you could also directly return the task from FirstOrDefaultAsync(without awaiting it due to await only being usable in an async method)
domi
  • 362
  • 4
  • 6