【发布时间】:2019-11-14 05:14:31
【问题描述】:
我想查询一个数据库表。我想知道是否可以通过将表达式传递给 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 => ...);
【问题讨论】:
-
看
Select方法的签名,需要传入正确的东西... -
你可以传入一个列的字符串(由分隔符分隔,如','),但这不是类型安全的方式
-
Expression<Func<TEntity, List<TEntity>>>? -
不,更像这个:
Select<TSource, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector)。请注意,Select方法不必返回您的实体,它可以是 DTO、int或完全不同的东西。 -
Select 的签名是
Select<TSource,TResult>()这意味着调用代码应该知道源实体和结果实体。因此,该方法也可以利用仅提供IQueryable<TSource>的方法,并在其自身的主体中应用 Select 而不是跳过箍将其作为参数传递。我的意思是,它并没有改进任何封装,那么有什么好处呢?
标签: c# asp.net-web-api async-await entity-framework-6