Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FirstOrDefaultAsync() in async await WEB API's

I have created one .NET Core API , where my all methods are asynchronous but there is one requirement like GetBalance() which just return one entity (record) only.

I am not able to using SingleOrDefaultAsync(), getting error like does not contain a definition for this.

I am using simple basic EF Code First approach with no Repository pattern.

Here is my code example.

public async Task<ResponseBalanceModel> GetBalanceFor(int accountNumber)
{
    var result = await _dbContext.Accounts.Where(x => 
             x.AccountNumber == accountNumber)
             .SingleOrDefaultAsync(); // this is not working.

    /*Below tried code are not working. 
    var result1 = await _dbContext.Accounts.Where(x => x.AccountNumber == accountNumber).SingleOrDefaultAsync();

    var result2 = await _dbContext.Accounts.FirstOrDefaultAsync(x => x.AccountNumber == accountNumber);
    */
 }

For more clarification

enter image description here

Reference of Entityframework in my project. (.NET Core)

enter image description here

like image 320
vijay sahu Avatar asked Aug 08 '18 09:08

vijay sahu


Video Answer


1 Answers

The EF Core async extension methods are defined in the Microsoft.EntityFrameworkCore namespace. This namespace must be imported for the methods to be available.

like image 81
Niraj Trivedi Avatar answered Sep 19 '22 10:09

Niraj Trivedi