C# 是否可以将select作为表达式传递以生成投影DbSet?
我想查询数据库表。我想知道是否可以通过将表达式传递给DbSet来使用投影 我的问题是:C# 是否可以将select作为表达式传递以生成投影DbSet?,c#,asp.net-web-api,async-await,entity-framework-6,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() {
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();
}
我只是省略了select(projection)部分,并实现了一个通用存储库的方法,如下所示:
public virtual async Task<List<TEntity>> GetGamesAsync(
Expression<Func<TEntity, bool>> where)
{
return await dbSet.Where(where).ToListAsync();
}
这是我的问题的解决方案,我使用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);
var config=new-MapperConfiguration(cfg=>
{
CreateMap();
CreateMap();
});
var iMapper=config.CreateMapper();
var gameBankConfirmResponse=iMapper.Map(gameBankConfirmResult);
现在我所需要的就是用Unity来整理周围的所有映射:)希望有人能帮助我
我肯定需要以下内容:
查看
Select
方法的签名,您需要传入正确的内容…您可以传入一个列字符串(由诸如“,”之类的分隔符分隔),但这不是类型安全的方式表达式
?不,更像这样:Select(此IQueryable源代码,表达式选择器)
。请注意,Select
方法不必返回您的实体,它可以是DTO、或int
或完全不同的东西。Select的签名是Select()
,这意味着调用代码应该知道源实体和结果实体。因此,该方法也可以利用一个只提供IQueryable
的方法,并在自己的主体中应用Select,而不是跳转,将其作为参数传递。我的意思是,它不会改进任何封装,那么它有什么好处呢?
//Query GameBank database
var gameBankResult =
await _unitOfWork.GameBankRepository.GetGamesAsync(g =>
g.productCode == requestDto.productCode && g.referenceId == null);
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);