· problem solving · 2 min read
Async methods in Entityframeworkcore

preview
Recently, I have updated my code base into dot net 8. While doing integration with Entityframework I faced some issue.I fixed it with ramdom solutions.
Samples
the below code excuted and get response as we expected from Get Api.
without async method:
[HttpGet]
public Employees AllEmployees(int? bussinessId)
{
var employees=new Employees[];
try
{
employees = _context.Employees
.FirstOrDefault(x => x.BusinessEntityId == bussinessId);
return response;
}
catch (Exception ex)
{
return employees;
}
}
With Async method:
I tried with below code with db context. I’m getting below Exception
Exception: The provider for the source IQueryable doesn’t implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations. For more details see http://go.microsoft.com/fwlink/?LinkId=287068.
[HttpGet("GetAllEmployeesAsync")]
public async Task<Employees> GetAllEmployeesAsync(int? bussinessId)
{
var response = new Employees();
try
{
response = await _context.Employees
.FirstOrDefaultAsync(x => x.BusinessEntityId == bussinessId);
return response;
}
catch (Exception ex)
{
return response;
}
}
How I fixed it?:
With the below change I fixed the Code issue.
[HttpGet("GetAllEmployees")]
public async Task<Employees> AllEmployees(int? bussinessId)
{
var response = new Employees();
try
{
response =
await EntityFrameworkQueryableExtensions
.FirstOrDefaultAsync(QueryableExtensions
.AsNoTracking(_context.Employees).Where(x => x.BusinessEntityId == bussinessId));
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return response;
}
}
Is this only way to fix this issue ? Nope. EntityframeworkCore has other generic fashion solution might be there. Since , I haven’t aware of this ,just logging for my future reference. If any one aware of this please share your fix and feed back to enhance it.
Git:https://github.com/tmanikandanmca/Onlinestore.Api
If you have can able to help me , please glone above link. Datadase : Adventureworks