应该将构建查询到数据库的同步操作包装到Task.FromResult中

问题描述

我有一个代码,我感觉(但不太确定)里面有代码的味道:

方法调用存储库方法GetAllByOrderIdAsync

List<IncomingBatch> incomingBatches = 
            (await _incomingBatchRepository.GetAllByOrderIdAsync(orderId)).ToList();

存储库类:

internal class IncomingBatchRepository : EfBaseEntityRepository<IncomingBatch>,IIncomingBatchRepository
{
    public IncomingBatchRepository(WarehouseMSsqlContext context) : base(context)
    {
    }

    // actually my concerns about this method
    public async Task<IEnumerable<IncomingBatch>> GetAllByOrderIdAsync(Guid incomingOrderId)
    {
        return await Task.Fromresult(Entities.Join(_context.IncomingOrderGoods
                .Where(goods => goods.IncomingOrderId == incomingOrderId),batch => batch.Id,goods => goods.IncomingBatchId,(batch,goods) => batch));
    }
}

Entities来自基础存储库类,其类型为DbSet<T>

public abstract class EfBaseEntityRepository<T> : IRepository<T>
    where T : BaseEntity
{
    // ctor omitted for brevity

    protected virtual DbSet<T> Entities => _context.Set<T>();

    // another methods omitted for brevity
}

所以我在这代码中不喜欢GetAllByOrderIdAsync不是真正的异步方法。据我了解,它是同步建立查询的。

我正在考虑如下重构该代码

List<IncomingBatch> incomingBatches =
            await _incomingBatchRepository.GetAllByOrderIdAsync(orderId);

并将返回类型更改为List<IncomingBatch>并在此处执行查询

internal class IncomingBatchRepository : EfBaseEntityRepository<IncomingBatch>,IIncomingBatchRepository
{
    public IncomingBatchRepository(WarehouseMSsqlContext context) : base(context)
    {
    }

    public async Task<List<IncomingBatch>> GetAllByOrderIdAsync(Guid incomingOrderId)
    {
        return await
            Entities.Join(_context.IncomingOrderGoods
                .Where(goods => goods.IncomingOrderId == incomingOrderId),goods) => batch)
             .ToListAsync();
    }
}

您如何看待所有这些?原始代码中是否有任何代码异味?我应该重构它还是没有理由要担心?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)