复杂嵌套Linq查询

时间:2015-09-21 21:14:29

标签: c# .net entity-framework linq linq-to-sql

我希望找到所有处于提交状态并在指定日期之前提交的费用报告("天")。 有更好的(更快,更容易,更清洁)的方法吗?

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;
          }
    }

1 个答案:

答案 0 :(得分:0)

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

但我认为它会起作用

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();