Notbad
Notbad

Reputation: 6296

Is First method async in Linq?

I'm pretty new to dotnet asp core and would like to use async methods to talk with the database to follow good practices.

In a scenario I'm facing I need to retrieve First record of a table that matches a condition. It could or could not exist. So, I use the method using Entity Framework dbContext.mytable.First but it seems it isn't asyncronous.

Should I get rid of it and just use dbContext.mytable.FindAsync?

Upvotes: 0

Views: 613

Answers (1)

Nkosi
Nkosi

Reputation: 247018

You are probably missing a reference

EntityFrameworkQueryableExtensions.FirstAsync Method

note the namespace and assembly

Namespace:    Microsoft.EntityFrameworkCore
Assembly:    Microsoft.EntityFrameworkCore.dll

That should allow the use of FirstAsync

var result = await dbContext.mytable.FirstAsync(x => x.property == something);

If there is a possibility that the record does not exist then use FirstOrDefaultAsync

var result = await dbContext.mytable.FirstOrDefaultAsync(x => x.property == something);

Upvotes: 1

Related Questions