public virtual System.Net.Http.HttpResponseMessage GetWithPreviousTransaction([FromUri] int skip, [FromUri] int top) { var now = RockDateTime.Now; // Get all the active schedules on the page (determined by params) ordered by ID var schedules = Service.Queryable() .AsNoTracking() .Include(s => s.FinancialPaymentDetail) .Include(s => s.ScheduledTransactionDetails) .Where(s => s.IsActive && (!s.NumberOfPayments.HasValue || s.Transactions.Count < s.NumberOfPayments) && (!s.EndDate.HasValue || s.EndDate >= now) && s.StartDate <= now) .OrderBy(s => s.Id) .Skip(skip) .Take(top) .ToList(); // Extract the schedule IDs for the most recent transaction query var scheduleIds = schedules.Select(s => s.Id).ToList(); // Get the most recent transactions for each schedule var mostRecentTransactions = new FinancialTransactionService(Service.Context as RockContext).Queryable() .AsNoTracking() .Where(t => t.ScheduledTransactionId.HasValue && scheduleIds.Contains(t.ScheduledTransactionId.Value)) .GroupBy(t => t.ScheduledTransactionId) .Select(g => g.OrderByDescending(t => t.TransactionDateTime).FirstOrDefault()) .ToDictionary(t => t.ScheduledTransactionId.Value, t => t); // Build an object for each schedule to return to the user var schedulesWithMostRecentTransaction = schedules.Select(s => new { Schedule = s, MostRecentTransaction = mostRecentTransactions.GetValueOrNull(s.Id) }).ToList(); var response = ControllerContext.Request.CreateResponse(HttpStatusCode.OK, schedulesWithMostRecentTransaction); return(response); }