SelectMany in Entity Framework Core

SelectMany in Entity Framework Core is an operator that flattens out the collection of collections into one single collection of objects. It is a very useful operator with many use cases.

Database:
The Database for this tutorial is taken from the chinook database.
Source Code:
The source code of this project available in GitHub. It also contains the script of the database

Example Query

Consider the following query. The query returns list of Customers along with their Invoices.

We can write the above query in Entity Framework Core as follows. The query returns the collection of Customers. Under each Customer we have collection of Invoices. The result is a collection of collections.

SelectMany

The selectMany helps flattens out the collection of collections into one single collection of objects. Now let use re write the above query using the selectMany

In the example below Customersis the first or outer collection. We use the SelectMany method on the Customers collection

We need to choose the second or inner collection as the first argument to the SelectMany, which is Invoices

Next, we need to choose the shape of our output using a projection query. The lambda expression gets two arguments. The first argument is a reference to the outer collection (Customers). The second is a reference to the inner collection (Invoices).

The query returns a single collection, which is similar to what you get when you execute the SQL

SelectMany Multiple collections

You can chain of selectMany methods as shown below.

In our first SelectMany, we have included InvoiceLinecollection in the projection. The result of this projection becomes outer collection for the next SelectMany

Now in the second selectMany we can flatten it again into a single collection.

Also note that in the final projection we have included Track.Name and Track.Album.Title.They are reference navigational properties and not collections. Hence we do not have to use SelectMany on them.

References

Summary

SelectMany converts collection of collections into one single collection of objects. You can also use it flatten the multiple hierarchical collections into a single collection.

2 thoughts on “SelectMany in Entity Framework Core”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top