c# - EF6 - Return calculated grouped results within a single query -


i have usage table stores daily usage customers of various products. want return result groups results customerid total / combined usage of various products.

see below illustrated example of current data structure :)

  • id | customerid | prod1 | prod2
  • 1 . 123 . 0 . 1
  • 2 . 125 . 5 . 5
  • 3 . 125 . 1 . 1

i looking return result set such (again, admire illustrating ability):

  • customerid | prod1 | prod2
  • 123 . 0 . 1
  • 125 . 6 . 6

will kind of calculation possible using ef? trying avoid multitude of loops achieve same thing brother out.

what need groupby , sum:

var result = context.customers     // .where(filter) // filter if needed     .groupby(m => m.customerid)     .select(g => new      {         customerid = g.key, // grouped according customerid, key = customerid         sumprod1 = g.sum(m => m.prod1), // sum prod1 of grouped data         sumprod2 = g.sum(m => m.prod2) // sum prod2 of grouped data     })     .tolist();  

note: tolist() retrieving data, not needed if plan work on query.


Comments