But how to get the grouped data (i.e nested lists) using EF Core in Web API?
As far as I'm aware, you can't. The documentation says:
The SQL query can't contain related data. However, in many cases you can compose on top of the query
And it says
Composing with LINQ requires your raw SQL query to be composable since EF Core will treat the supplied SQL as a subquery. ...
SQL Server doesn't allow composing over stored procedure calls
All in, you having written a sproc that does SELECT * FROM a. JOIN b ON ...
there is then no way for you to say context.A.FromSqlInterpolated("...")
and get EF to give you a bunch of A objects with all their related B lists filled out. When you run a normal query like context.A.Include(a => a.B)
EF will know what it has requested so it can map the a.* columns to instances of A and the b.* columns to instances of B (simplistically if EF does SELECT a.One, a.Two, b.One, b.Two FROM a JOIN b
, it can know the first two columns should be mapped to A instances and the second two to B instances, and it can track A's it has seen before and build a graph of related entities) but just being straight up given a result set and told to map it to a graph of objects isn't going to be universally possible (suppose your sproc does SELECT a.One, a.Two, b.One, b.Two FROM a JOIN b
- all EF will see is a result set of "One, Two, One, Two" - how can that certainly be mapped to A:B? And which way round? And what if C has a column One also? ..)
You could consider using Dapper; it will be able to run the sproc, get the table of data and unpack it to A and B (and C etc) per row using its split-on feature and then it's down to you build a tree of objects (dapper calls a method you provide, to build the tree)..
..but then you'll have bought the EF dog and be barking yourself. If you've done this everywhere (used stored procedures full of joins) there seems little point in using EF..
You could perhaps adopt a similar "roll your own" approach where you make an entity that has all the properties that A, B and C do, and then get EF to fill out a collection of it, and then post process it to look for all the repeated A and B and build dictionaries of them to reconstruct the graph; but then you're rebuilding what EF does, which also gets back to the "there's little point using EF"