Entity Framework 核心 IEnumerable 异步

Entity Framework Core IEnumerable async

我已经在我的项目中实现了一个存储库模式,并且有一个 CoinRepository,我想添加一个新方法 (GetValues),它根据来自的条件仅检索一列(值)硬币 table 有多个列。

这里是 CoinRepositopry class 和方法。

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接口中的一个方法returns一个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. 如果我的代码有问题,速度不够快,我该如何修改和重构到最优化的方式?

谢谢

Should I make the GetValuesAsync an async method?

是的,绝对是。异步一直传播到调用堆栈。通过访问 Result,您将阻塞线程并破坏异步的目的。

Does the GetAllAsync method execute a query in the database, retrieve all the records and then apply the condition in the code or execute the query in the database like this SELECT c.value FROM COIN c WHERE?

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

If my code has problems and it is not fast enough, how can I modify it and refactor it in the most optimal way?

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 列。