linq 在EF Core中重用where条件

wnvonmuf  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(168)

我在EF Core 6中有这个IQueryable,并试图重构它,因为我想有单独的方法,当我通过IGrouping时,它可以计算特价或旅行费用,并将其插入IQueryable中。这可能吗?我想要一些不可能的东西。
这是查询:

var splitQuery = joinedWithFees.GroupBy(q => new
        {
            q.CarrierId,
            q.ProfitCenterId,
         })
        .Select(g => new CarrierReportDto
        {
            CarrierId = g.Key.CarrierId,
            Standard = g.Where(x => x.IsInSplit)
                .Sum(x => x.SettlementAmount),
            Specials = g.Where(x => x.IsInSplit)
                .Where(x => isNotInvoiced && !x.SettlementId.HasValue || !isNotInvoiced)
                .Where(x => !startDate.HasValue || x.FeeDate >= startDate && !endDate.HasValue || x.FeeDate <= endDate)
                .Where(x => x.GroupId == (int)FeeTypeGroups.Special)
                .Sum(x => x.SettlementAmount),
            TravelPay = g.Where(x => x.IsInSplit)
                .Where(x => isNotInvoiced && !x.SettlementId.HasValue || !isNotInvoiced)
                .Where(x => !startDate.HasValue || x.FeeDate >= startDate && !endDate.HasValue || x.FeeDate <= endDate)
                .Where(x => x.GroupId == (int)FeeTypeGroups.TravelTeam)
                .Sum(x => x.SettlementAmount)
       };,

我想重用其中的一些条件,我该怎么做呢?
例如这个:

x => isNotInvoiced && !x.SettlementId.HasValue || !isNotInvoiced

如果我像这样使用Expression

Expression<Func<Model, bool>> pred = x => isNotInvoiced && !x.SettlementId.HasValue || !isNotInvoiced

编译前或编译时都会失败,因为EF不能这样做。
有人能帮我吗?

dtcbnfnu

dtcbnfnu1#

在过滤前尝试使用AsQueryable

Expression<Func<Model, bool>> pred = x => isNotInvoiced && !x.SettlementId.HasValue || !isNotInvoiced

// ...

Specials = g.AsQueryable().Where(pred)

没有测试对EF核心6,但EF核心7简单的复制作品。
你也可以尝试使用LINQKit,就像在this asnwer中一样。

相关问题