复杂嵌套Linq查询

本文关键字:查询 Linq 嵌套 复杂 | 更新日期: 2023-09-27 18:13:53

我正在查找处于提交状态并在给定日期("days")之前提交的所有费用报告。有没有更好(更快、更容易、更干净)的方法来做这件事?

var startDate = DateTime.Now.AddDays(-days);
using (var context = new Context())
{
    var data = context.tExpenseReports
                    .AsNoTracking()
                    .Where(r => context.tTransactionStatuses.FirstOrDefault(s => s.TransactionStatusID == r.tTransactions.Max(t => t.TransactionStatusID)) != null ?
                                context.tTransactionStatuses.FirstOrDefault(s => s.TransactionStatusID == r.tTransactions.Max(t => t.TransactionStatusID)).TransactionStatusID == IDConstants.TRANSACTION_STATUS_SUBMITTED &&
                                context.tTransactionHistories.FirstOrDefault(s => s.TransactionStatusID == r.tTransactions.Max(t => t.TransactionStatusID)).CreatedDatetime < startDate
                                : false)
              .Execute()
              .Select(Mapper.Map<tExpenseReport,ExpenseReport>)
              .ToArray();
              return data;
          }
    }

复杂嵌套Linq查询

我不确定我理解你所有的方法

但我认为它会起作用

var sata1=( from r in context.tExpenseReports.AsNoTracking()
                       let max = r.tTransactions.Max(t => t.TransactionStatusID)
                       let s = context.tTransactionStatuses.FirstOrDefault(s => s.TransactionStatusID == max)
                       where s!=null
                       where s.CreatedDatetime < startDate
                       select r);
          return  sata1 .Execute()
              .Select(Mapper.Map<tExpenseReport,ExpenseReport>)
              .ToArray();