首页 > 解决方案 > 实体框架核心 IEnumerable 异步

问题描述

我已经在我的项目中实现了一个存储库模式,CoinRepository并且我想添加一个新方法(GetValues

这是CoinRepositopry类和方法。

public class CoinRepository : Repository<Coin>, ICoinRepository
{
    public CoinRepository(MyContext context) : base(context) { }

    public IEnumerable<decimal> GetValuesAsync(int gameId, int gameTableId, string partnerCurrencyId)
    {
        return GetAllAsync().Result
            .Where(c => c.GameId == gameId && c.CurrencyId == partnerCurrencyId)
            .Select(c => c.Value);
    }
}

GetAllAsync方法是IRepository接口中的一个方法,它返回一个Task <IEnumerable<Entity>>.

public async Task<IEnumerable<T>> GetAllAsync(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = null)
{
        IQueryable<T> query = dbSet;

        if (filter != null)
            query = query.Where(filter);

        if (includeProperties != null)
            foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                query = query.Include(includeProperty);

        if (orderBy != null)
            return await orderBy(query).ToListAsync();

        return await query.ToListAsync();
}

我的问题是:

  1. 我应该制作GetValuesAsync一个async方法吗?

  2. GetAllAsync方法是在数据库中执行查询并检索所有记录,然后在代码中应用条件 - 还是像这样在数据库中执行查询SELECT c.value FROM COIN c WHERE <condition>

  3. 如果我的代码有问题并且速度不够快,我该如何修改它并以最优化的方式重构它?

谢谢

标签: c#asp.net-coreasync-awaitentity-framework-corerepository-pattern

解决方案


我应该制作GetValuesAsync一个async方法吗?

当然是。异步在调用堆栈中一直向上传播。通过访问Result您正在阻塞线程并破坏异步的目的。

GetAllAsync方法是在数据库中执行查询,检索所有记录,然后在代码中应用条件还是像这样在数据库中执行查询SELECT c.value FROM COIN c WHERE

您尚未提供表达式,Where因此它将从数据库中检索所有行并在内存中进行过滤。

如果我的代码有问题并且速度不够快,我该如何修改它并以最优化的方式重构它?

public class CoinRepository : Repository<Coin>, ICoinRepository
{
    public CoinRepository(MyContext context) : base(context) { }

    public async Task<IEnumerable<decimal>> GetValuesAsync(int gameId, int gameTableId, string partnerCurrencyId)
    {
        var coins = await GetAllAsync(c => c.GameId == gameId && c.CurrencyId == partnerCurrencyId,
            includeProperties: nameof(Coin.Value));
        return coins.Select(c => c.Value);
    }
}

这样,您将一个表达式传递给该表达式,该表达式GetAllAsync可用于生成 SQL where 子句,并仅指定Value要检索的列。


推荐阅读