简体   繁体   中英

Complex Nested Linq Query

I'm looking to find all expense reports that are in a submitted state and were submitted prior to a given date ("days"). Is there a better (faster, easier, cleaner) way to do this?

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

I am not sure I understand all your methods

But I think it will work

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM