Skip to content

Instantly share code, notes, and snippets.

@BryanWilhite
Last active August 29, 2015 14:09
Show Gist options
  • Save BryanWilhite/b3d028ffe83c2e82bc48 to your computer and use it in GitHub Desktop.
Save BryanWilhite/b3d028ffe83c2e82bc48 to your computer and use it in GitHub Desktop.
C#, EF: The 'hard' way to get JOIN...
static class Sample
{
/// <summary>
/// Queries the requisitions.
/// </summary>
public static IQueryable<Requisition> QueryRequisitions()
{
var ctx = GetContext();
var statusIdsQuery = ctx.OrderStatuses
.Select(i => i.OrderStatusId);
var orderIdsQuery = ctx.OrderDetails
.Where(i => i.BusinessType == "R")
.Select(i => i.OrderID);
var rentalChildrenQuery = XavierContext.QueryRentalChildren()
.Select(i => i.OrderId);
var query = ctx.OrderHeaders
.Include("OrderDetails")
.Where(i => i.OrderId != null)
.Where(i => i.RequisitionType == "R")
.Where(i => statusIdsQuery.Contains(i.OrderStatusID))
.Where(i => !orderIdsQuery.Contains(i.OrderId))
.Where(i => i.IsRentalParent == false)
.Where(i => !rentalChildrenQuery.Contains(i.OrderId))
.Join(ctx.Departments,
oh => oh.DepartmentID,
dept => dept.DepartmentID,
(oh, dept) => new {oh, dept})
.Join(ctx.OrderStatuses,
join => join.oh.OrderStatusID,
status => status.OrderStatusId,
(join, status) => new { join, status })
.Join(ctx.OrderDetails,
join => join.join.oh.OrderId,
detail => detail.OrderID,
(join, detail) => new { join, detail })
.OrderByDescending(i => i.join.join.oh.OrderId)
.Select(i => new Requisition
{
OrderId = i.join.join.oh.OrderId,
OrderNumber = i.join.join.oh.OrderNumber,
PONumber = i.join.join.oh.PONumber,
DepartmentName = i.join.join.dept.DepartmentName,
CustomerName = i.join.join.oh.CustomerName,
CreatedDt = i.join.join.oh.CreatedDt,
PriorityFl = i.join.join.oh.PriorityFl,
OrderStatusDescription = i.join.status.StatusDescription,
CreatedBy = i.join.join.oh.CreatedBy,
OrderTotal = i.join.join.oh.OrderDetails.Sum(j => j.TotalAmount)
});
return query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment