实体框架核心IEnumerable异步

时间:2020-07-14 13:27:37

标签: c# asp.net-core async-await entity-framework-core repository-pattern

我已经在我的项目中实现了存储库模式,并且有一个CoinRepository,我想添加一个新方法(GetValues),该方法仅基于Coin中的条件检索一个列(值)有多列的表格。

这里是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. 如果我的代码有问题并且速度不够快,我该如何修改它并以最佳方式对其进行重构?

谢谢

1 个答案:

答案 0 :(得分:3)

我应该使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列。

相关问题