public ServiceResponse GetOrdersForGrid(UserSessionModel user, SearchOrders search) { search.ReturnTotals = true; //var query = from order in this.Context.Orders var query = from order in this.Db.QueryOrderViewableBySearch(user, search)// TODO: this QueryOrderViewableBySearch is very slow. It can cause time out error with super user join project in this.Db.Projects on order.Quote.ProjectId equals project.ProjectId join quote in this.Db.Quotes on order.QuoteId equals quote.QuoteId join discountRequest in this.Context.DiscountRequests on new { project.ProjectId, quote.QuoteId } equals new { discountRequest.ProjectId, discountRequest.QuoteId } into Dr from discountRequest in Dr.OrderByDescending(o => o.Timestamp).Take(1).DefaultIfEmpty() join commissionRequest in this.Context.CommissionRequests on new { project.ProjectId, quote.QuoteId } equals new { commissionRequest.ProjectId, commissionRequest.QuoteId } into Cr from commissionRequest in Cr.OrderByDescending(o => o.Timestamp).Take(1).DefaultIfEmpty() select new OrderGridViewModel { projectId = project.ProjectId, projectName = project.Name, orderId = order.OrderId, poNumber = order.PONumber, erpOrderNumber = order.ERPOrderNumber, poAttachmentName = order.OrderAttachments.FirstOrDefault().FileName, projectOwnerName = project.Owner.FirstName + (project.Owner.MiddleName != null ? " " + project.Owner.MiddleName : "") + " " + project.Owner.LastName, dealerContractorName = project.DealerContractorName, orderStatusTypeId = (OrderStatusTypeEnum)order.OrderStatusTypeId, quoteId = quote.QuoteId, activeQuoteTitle = quote.Title, businessId = project.Owner.BusinessId, businessName = project.Owner.Business.BusinessName, projectDate = project.ProjectDate, submitDate = order.SubmitDate, estimatedDeliveryDate = project.EstimatedDelivery, estimatedReleaseDate = order.EstimatedReleaseDate, ERPShipDate = order.ERPShipDate, pricingTypeId = quote.IsCommission ? (byte)2 : (byte)1, totalNetPrice = quote.TotalNet, totalListPrice = quote.TotalList, totalSellPrice = quote.TotalSell, //totalDiscountPercent = quote.DiscountPercentage, totalDiscountPercent = quote.ApprovedDiscountPercentage, darComStatus = quote.IsCommission ? (commissionRequest != null ? commissionRequest.CommissionRequestStatusType.Description : "") : (discountRequest != null ? discountRequest.DiscountRequestStatusType.Description : ""), vrvODUcount = quote.VRVOutdoorCount, splitODUcount = quote.TotalCountSplitOutdoor, submittedByUserId = user.UserId, submittedByUserName = user.LastName + ", " + user.FirstName, createdByUserId = user.UserId, updatedByUserId = user.UserId, OrderReleaseDate = order.OrderReleaseDate }; this.Response.Model = query.ToList(); return(this.Response); }