I have the following query working fine in LINQ to SQL. Now I want to change it to Entity Framework
var _sale = from emp in setupEmployees
join sales in vwSaleTargets on emp.EmployeeID equals sales.EmployeeID
join price in vwPeriodPricings
on new { sales.SKUID, sales.PeriodID }
equals new { SKUID = (int?)price.SKUID, PeriodID = (int?)price.PeriodID }
join sk in setupSKUs on sales.SKUID equals sk.SKUID
join br in setupBrands on sk.BrandID equals br.BrandID
where emp.EmployeeID == 123 && sales.StartDate.Year == 2012
select new { emp, sales, price, sk, br };
var lstSale = _sale.ToList(); //to avoid n+1 queries in case of grouping
var sale2 = from x in lstSale
group x by new { x.sk, x.emp } into grouping
select new
{
EmployeeName = grouping.Key.emp.EmployeeName,
SKUID = grouping.Key.sk.SKUID,
SKUName = grouping.Key.sk.Title,
MonthSale =(double?)grouping
.Where(x => x.sales.StartDate.Month == 2 &&
x.sales.StartDate.Year == 2012)
.Select(t=>t.sales.SalesQuantity)
.Sum(t=>t.Value)?? 0,
MonthSaleValue = (double?)grouping
.Where(x => x.sales.StartDate.Month == 2 &&
x.sales.StartDate.Year == 2012)
.Sum(x => x.sales.SalesQuantity * x.price.ExFactoryPrice)
?? 0,
};
Console.WriteLine(sale2.OrderBy(x => x.SKUName).ToList());
In Entity Framework It is giving me result Like this
Name SKUID SKUName MonthSale MonthSaleValue
EMP1 36 SKU1 113 61375.95
EMP1 17 SKU2 113 6656.83
EMP1 18 SKU3 113 9984.68
EMP1 19 SKU4 113 15169.12
In L2S I am getting me correct result like this
Name SKUID SKUName MonthSale MonthSaleValue
EMP1 36 SKU1 74 40193.1
EMP1 17 SKU2 113 6656.83
EMP1 18 SKU3 461 40733.96
EMP1 19 SKU4 2 268.48
Regards
As an approach to finding the answer…
To diagnose, as suggested by @Jon Skeet, you need to simplify it AND look at what you’re getting within lstSale to compare LINQ to SQL to EntityFramework.
So something along the following lines may help (not necessarily syntactically correct because I haven’t got all your source objects to check, however I’m just looking at the query and simplifying it down where it appears you can)
Changes (which may not all be valid):
1. Removed branding since it isn’t consumed in the second query (you could use it as a join in the first but not add to the new type if its part of the restriction)
2. Simplified what’s included in the anonymous type generated by the first query – if you’re only consuming parts of emp/sales/price then it may make it clearer as to what’s going on
3. Added restriction to SalesMonth in the first part (what you’re doing in the second) because that may reduce your data, increase performance and allow you to focus on what’s actually going wrong (I have left the second SalesMonth restriction in place)
4. I assume SKUID is the relevant part of sk for grouping and not all of the object is required