Derrick
Derrick

Reputation: 71

How to await (in async method) a linq request containg a c# method call

I'm implementing a Get method in an API, and Im performing a linq (Linq to Entity) request to a database:

  var result = db.SomeEntity
             .ToList()
             .Select(a => new {a, Rank(a, key})
             .Where(obj => obj.Rank > 0));

Where the method Rank returns an Integer based on some property in a. In other words I'm wrapping an object in a new object with its associated rating.

Since its a Get method in an API it would be nice to make it async and await the linq query. The problem is that I have to call ToList before Select so the Select method doesnt have to translate to SQL (in order for the Rank method call to work ), and because of that Im not able to use ToListAsync after the Where function

E.g.

await (db.Some.....Where(..)).ToListAsync()

I'm unsure about how to go about this. Any suggestions?

Upvotes: 2

Views: 1507

Answers (1)

David
David

Reputation: 218828

Im not able to use ToListAsync after the Where function

You can still await the DB operation, just wrap the operation in parentheses so the overall result is the correct type:

var result = (await db.SomeEntity.ToListAsync())
         .Select(a => new {a, Rank(a, key})
         .Where(obj => obj.Rank > 0));

Conversely, you can perform the overall operation in two steps:

var list = await db.SomeEntity.ToListAsync();
var result = list.Select(a => new {a, Rank(a, key})
                 .Where(obj => obj.Rank > 0));

It's the same thing either way, really. The Select and Where don't do anything asynchronous in this case, so there's nothing else to await. Your DB operation is happening on the .ToList(), not on the .Where().

Note: If it's at all possible to perform the Rank() logic in a LINQ-to-Entities expression tree, that would likely be a better overall option. Even if it makes the logic more complicated, if the count of SomeEntity ever reaches just about any significant amount then the performance benefits are clear.

Upvotes: 3

Related Questions