简体   繁体   English

如何等待(在异步方法中)包含ac#方法调用的linq请求

[英]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: 我正在API中实现Get方法,并且我正在对数据库执行linq(Linq to Entity)请求:

  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. 方法Rank根据a中的某个属性返回Integer。 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. 由于它是API中的Get方法,因此将其设置为异步并等待linq查询会很好。 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 问题是我必须在Select之前调用ToList,因此Select方法不必转换为SQL(为了使Rank方法调用起作用),并且因为我在Where函数之后无法使用ToListAsync

Eg 例如

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

I'm unsure about how to go about this. 我不确定如何解决这个问题。 Any suggestions? 有什么建议么?

Im not able to use ToListAsync after the Where function 我无法在Where函数之后使用ToListAsync

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. SelectWhere在这种情况下不做任何异步操作,所以没有别的东西可以等待。 Your DB operation is happening on the .ToList() , not on the .Where() . 您的数据库操作发生在.ToList() ,而不是.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. 注:如果这是在所有可能进行Rank()在LINQ到实体表达式树的逻辑,这将可能是一个更好的整体选择。 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. 即使它使逻辑变得更复杂,如果SomeEntity数量达到任何显着的数量,那么性能优势SomeEntity明显。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM