I need help with this, I have a very important piece of code that I got help with from this thread
The code is as follows:
var pln = db.tabStockPlanners
.Where(y => y.ExpectedHarvestDate < addoneyear)
.Where(r => r.Published == 1)
.Where(f => f.Available == 1);
var gruppedList = pln.GroupBy(x => x.ItemID, (key, enumerable) =>
{
return new tabStockPlanner { ItemID = key, ExpectedYieldInTonnes = enumerable.Sum(k => k.ExpectedYieldInTonnes) };
}).OrderByDescending(t => t.ExpectedYieldInTonnes).ToList();
But I get an error
A lambda expression with a statement body cannot be converted to an expression tree
I do not know if this is something that has changed with EF. Can someone help me with this? EF is version 6. Any issues with the current code?
UPDATE
What has worked perfectly is:
var gplist = from x in db.tabStockPlanners
where x.Published == 1
where x.Available == 1
where x.ExpectedHarvestDate < addoneyear
group x.ExpectedYieldInTonnes by new { x.ItemID }
into g
select new { g.Key.ItemID, ExpectedYieldInTonnes = g.Sum() };
But I would like to also have the correct answer as per this syntax. Maybe someone can repost with the LINQ syntax. Thank you.
UPDATE
Hello Friends; @YosefBinmal solution worked well, along with @NetMage proposal for AsEnumerable()
I am posting Yosef's solution with modifications to make it anonymous and return just the 2 columns needed. I removed the tabStockPlanner
so its new {
and it is solid. So marking that as correct. Any objections? It works well.
Here's the modified code
var pln = db.tabStockPlanners
.Where(y => y.ExpectedHarvestDate < addoneyear)
.Where(r => r.Published == 1)
.Where(f => f.Available == 1);
var gruppedList = pln
.AsEnumerable()
.GroupBy(i => i.ItemID)
.Select(g => new { ItemID = g.Key, ExpectedYieldInTonnes = g.Sum(i => i.ExpectedYieldInTonnes) })
.OrderByDescending(t => t.ExpectedYieldInTonnes)
.ToList();