【发布时间】:2019-12-15 15:16:19
【问题描述】:
我正在学习 Linq。该示例使用 Northwind 数据库。我正在尝试使以下方法异步:
public IActionResult ProductsThatCostMoreThan(decimal price)
{
var model = db.Products
.Include(p => p.Category)
.Include(p => p.Supplier)
.AsEnumerable()
.Where(p => p.UnitPrice > price);
return View(model);
}
如果尝试了下面的代码,但编译器抱怨IAsyncEnumerable<Product> 不包含Where 的定义,并且找不到接受IAsyncEnumerable<Product> 类型的第一个参数的可访问扩展方法“Where”。删除 where 表达式可解决此问题。如何编写异步 where 过滤器?
public async Task<IActionResult> ProductsThatCostMoreThanAsync(decimal price)
{
var model = await db.Products
.Include(p => p.Category)
.Include(p => p.Supplier)
.AsAsyncEnumerable()
.Where(p => p.UnitPrice > price);
return View(model);
}
尝试澄清:我将尝试更好地解释问题的上下文。这是一本书的学术练习,我正在尝试从中学习 Linq。
该方法是 Asp.net Core MVC 网站中的控制器操作方法。我了解到,如果控制器操作方法很慢(例如,它需要从数据库中获取大量数据),它会限制网站的可扩展性,因为该方法会锁定 Web 服务器线程池中的一个线程,直到它完成。使控制器中的操作方法异步将线程释放回池中,以便在方法执行缓慢的操作时可以重用它。 (见https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/october/async-programming-introduction-to-async-await-on-asp-net)。
例如:
public IActionResult Index()
{
var model = new HomeIndexViewModel
{
Categories = db.Categories.ToList()
};
return View(model);
}
为此更改为以下内容:
public async Task<IActionResult> Index()
{
var model = new HomeIndexViewModel
{
Categories = await db.Categories.ToListAsync(),
};
return View(model);
}
我正在尝试对问题顶部的方法进行类似的更改。
【问题讨论】:
-
为什么要将所有数据加载到内存中?使用这个
db.Products... .Where(p => p.UnitPrice > price).AsEnumerable() -
请看我上面修改过的问题。
标签: c# asp.net-mvc entity-framework linq