问题描述
我正在尝试从数据库中获取记录,但是在对DB的同一调用中获得了记录计数.我的方法是异步的,所以我不确定这是否是正确的方法:
I'm trying to fetch records from database but in the same call to DB get record count. My methods are async so I'm not sure if this is the right way to do it:
public async Task<IEnumerable<ProductItemViewModel>> GetAsync(int pageIndex, int pageSize)
{
var products = this.Repository.GetAll<Product>().OrderBy(p => p.Price).AsQueryable();
var count = await products.CountAsync();
if (count == 0)
return new List<ProductItemViewModel>();
products = products.ToPaginatedList(pageIndex, pageSize);
var result = await products.ToListAsync();
var viewModels = new List<ProductItemViewModel>();
Mapper.Map(result, viewModels);
return viewModels.AsEnumerable();
}
我认为等待CountAsync()不太好,但是我不确定如何实现.
I think its not so good to await CountAsync() but I'm not sure how to implement it.
致谢.
我很抱歉没有在任何地方返回计数,因为现在看来我只因为== 0检查才进行计数,但是最终我将返回带有记录的计数,因为我的角度分页指令需要它.还没有弄清楚我将如何返回(新类vs元组),所以我错过了它,只专注于单个DB调用中的实体框架Count()和实体获取.
I apologize for not returning count anywhere, as it looks now that I only count because of that == 0 check, but I will eventually return count with records because I need it for my angular paging directive. Haven't figured it out how I will return (new class vs tuple) so I missed it out and focused on entity framework Count() and entity fetch in single DB call.
推荐答案
我认为您的代码可以对此进行优化:
I think your code can be optimized to this:
using AutoMapper.QueryableExtensions;
//...
public async Task<IEnumerable<ProductItemViewModel>> GetAsync(int pageIndex, int pageSize)
{
var products = this.Repository.GetAll<Product>().OrderBy(p => p.Price);// I think you don't need to call AsQueryable(), you already are working with IQueryable
var result=await products.Skip(pageIndex*pageSize).Take(pageSize).ProjectTo<ProductItemViewModel>().ToListAsync();
return result;
}
最后,只需一行就可以完成:
At the end it can be done in just one line:
public async Task<IEnumerable<ProductItemViewModel>> GetAsync(int pageIndex, int pageSize)
{
return await this.Repository.GetAll<Product>()
.OrderBy(p => p.Price)
.Skip(pageIndex*pageSize)
.Take(pageSize)
.ProjectTo<ProductItemViewModel>()
.ToListAsync();
}
.ProjectTo<ProductItemViewModel>()
将告诉AutoMapper的映射引擎向IQueryable
发出选择子句,该子句将通知Entity Framework它仅需要查询映射的属性,就如同您手动将IQueryable
投影到一个带有Select
子句的ProductItemViewModel
.
The .ProjectTo<ProductItemViewModel>()
will tell AutoMapper's mapping engine to emit a select clause to the IQueryable
that will inform Entity Framework that it only needs to query the properties that you mapped, same as if you manually projected your IQueryable
to an ProductItemViewModel
with a Select
clause.
这篇关于实体框架与记录的异步记录计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!