Marko Marko - 16 days ago 5
C# Question

Entify Framework - async select with where condition

I'm using ASP.NET Core with Entity Framework.

First I select an employee, and then all employees that satisfy a condition (for the purpose of displaying what works):

var a = db.Employee.FirstOrDefault();
var b = db.Employee.Where(x => x.FirstName == "Jack");


Now I try the same, but asynchronously:

var c = await db.Employee.FirstOrDefaultAsync();
var d = await db.Employee.Where(x => x.FirstName == "Jack");


However, for the "WHERE" there's no async version, and the second line of code doesn't compile - I get an error


... does not contain a definition for GetAwaiter ...


How do I perform a
SELECT
with a
WHERE
condition in this case?




OK, from the answers I see that ToListAsync() will resolve the "var d = ..." line. However, there's a continuation to this issue, I wasn't aware before that it matters. In this case I'm just trying to select a set of records that will be deleted, I'm not interested in accessing the data for the purpose of manipulating it further in the code. So I amended all 4 code versions with purpose to delete one or more records, synchronously or asynchronously. Why does only the last one need a ToListAsync(), won't that actually retrieve the records from the database?

var a = db.Employee.FirstOrDefault();
db.Employee.Remove(a);
// db.Employee.RemoveRange(a); <- this also works?
db.SaveChanges();

var b = db.Employee.Where(x => x.FirstName == "Jack");
db.Employee.RemoveRange(b);
db.SaveChanges();

var c = await db.Employee.FirstOrDefaultAsync();
db.Employee.Remove(c);
await db.SaveChangesAsync();

var d = await db.Employee.Where(x => x.FirstName == "Jack").ToListAsync();
db.Employee.RemoveRange(d);
await db.SaveChangesAsync();

Answer

You can do it like this.

If you need to retrieve one object then :

var d = await db.Employee.FirstOrDefaultAsync(x => x.FirstName == "Jack");

If you need to retrieve list then :

 var d = await db.Employee.Where(x => x.FirstName == "Jack").ToListAsync();
Comments