-2

I have some SQL code that I want to "convert" to an entity framework 'call'.

This is the code:

select  itemStatus, avg(UnitPrice) from ItemSalesHistory
where item = 'BQF09-L-Q007'
group by itemStatus

I'm new to using Entity Framework.

Karthik Ganesan
  • 4,142
  • 2
  • 26
  • 42
L. Levine
  • 145
  • 3
  • 16
  • 6
    Yes, did you Google this? "entity framework group by" has lots of results. Please see [How much research effort is expected of Stack Overflow users](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) –  Jul 18 '19 at 20:01
  • I did, but I didn't understand any of the results that I found. Why so serious ??? – L. Levine Jul 19 '19 at 13:33
  • In the future, show us what you've tried and what you didn't understand in your research. –  Jul 19 '19 at 13:38

1 Answers1

1

Yes you can. If you take a look at this answer, you can apply it to your situation:

var query = ItemSalesHistory
  .Where(x => x.item == 'BQF09-L-Q007')
  .GroupBy(x => x.itemStatus)
  .Select(g => new { itemStatus = g.Key, avg = g.Average(x => x.UnitPrice) });
Marko Papic
  • 1,846
  • 10
  • 23
  • Most of the EF code I've written returns a list (using the .ToList() option) that I save to a variable that is defined as a list that has the same "type" as the EF call itself. Does this call also return a list, and if so, what type ? I need to define a variable that will "hold" the results of this call, because this call is part of an if/else statement (both of which contains this EF code, though each call is slightly different) and as a such VS requires I define the variable first. – L. Levine Jul 19 '19 at 13:37
  • Ok. Progress is being made. I realized I can add .ToList to the EF code above. Still need to figure out how to declare the variable that will hold the results. – L. Levine Jul 19 '19 at 16:05
  • The result of this query will be a sequence of objects of anonymous type specified in the `Select`, so each item will have fields `itemStatus` and `avg`. – Marko Papic Jul 19 '19 at 19:50