是否可以将select作为表达式传递以进行投影DbSet?

时间:2019-07-03 13:33:24

标签: c# asp.net-web-api async-await entity-framework-6

我想查询数据库表。我想知道是否可以通过将表达式传递给DbSet来使用投影。

这是我的查询:

 var gameBankResultVM = await (context.GameBanks
                .Where(l => l.referenceId == confirm.referenceId)
                .Select(g => new GameBankConfirmResponseVM()
                {
                    referenceId = g.referenceId,
                    paymentId = null,
                    productCode = g.productCode,
                    quantity = g.quantity,
                    deliveredQuantity = g.quantity,
                    currency = g.currency,
                    version = g.version,
                    signature = g.signature,
                    ApplicationCode = g.ApplicationCode,
                    productDescription = g.productDescription,
                    unitPrice = g.unitPrice,
                    totalPrice = g.totalPrice,
                    totalPayablePrice = g.totalPrice,
                    coupons = g.coupons.Select(c => new GameCouponBankVM()
                    {
                        Pin = c.Pin,
                        Serial = c.Serial,
                        expiryDate = c.expiryDate
                    }).ToList()
                })).ToListAsync();

这就是我想要的;

public virtual async Task<List<TEntity>> GetGamesProjectionAsync(
            Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, bool>> select)
        {
            return await dbSet.Where(where).Select(select).ToListAsync();
        }

并根据我的查询预测调用此方法:

//Query GameBank database
                var gameBankResult =
                    await _unitOfWork.GameBankRepository.GetGamesAsync(g =>
                        g.productCode == requestDto.productCode && g.referenceId == null, t => ...);

1 个答案:

答案 0 :(得分:0)

我只是省略了select(投影)部分,并实现了通用存储库的方法,如下所示:

public virtual async Task<List<TEntity>> GetGamesAsync(
        Expression<Func<TEntity, bool>> where)
    {
        return await dbSet.Where(where).ToListAsync();
    }

我在我的业务服务层中称呼它

//Query GameBank database
            var gameBankResult =
                await _unitOfWork.GameBankRepository.GetGamesAsync(g =>
                    g.productCode == requestDto.productCode && g.referenceId == null);

这是我的问题的解决方案,我使用Automapper进行转换。

    var config = new MapperConfiguration(cfg =>
                {

                    cfg.CreateMap<GameBank, GameConfirmResponse>();
                    cfg.CreateMap<GameBankPin, Coupon>();
                });
                var iMapper = config.CreateMapper();
var gameBankConfirmResponse = iMapper.Map<IList<GameBank>, IList<GameConfirmResponse>>(gameBankConfirmResult);

现在我所需要的就是使用Unity整理周围所有的映射:)希望有人帮助我。

绝对需要以下内容:

grouping to generic method in Repository EF C#