Can I use Projections in EF Core…Absolutely!!

Before we drill into Projections, let’s find out what Projections really are:

Projection(s) is a powerful feature of LINQ that enables you to perform query operations on a data source, collection etc. It shapes the results of the data being queried into a different structure/format that the original data source is in.

It is a process to express queries in order to return a desired set of data other than the entire entity. Projection queries improve the efficiency of your application by only retrieving specific fields from your database.

A projection query lets you select only the data that is required from your model. It is done, by loading the data into a custom or anonymous type. This significantly improves the performance of your application, especially when you filter out the fields that contain huge amounts of data.

When you use the Select method, you can retrieve scalar properties and also navigation properties to retrieve data in the same query. Please see the code snippet below:

   private static void Projections()
        {
            using (var db = new demo_departmentContext())
            {
                var dept = db.Departments.Select(d => new { d.DepId, d.DepName, d.Location })
                    .Where(d => d.DepName.Contains("IT"))
                    .ToList();
                foreach (var item in dept)
                {
                    Console.WriteLine("{0} - {1} - {2}", item.DepId, item.DepName, item.Location);
                }
                Console.ReadLine();
            }
        }

And following is the output:

EFCoreProjectionsOutputAsΒ  you saw above using projectionsΒ allow us to retrieve a subset of the properties from an object as opposed to the entire object. This causes a smaller amount of data to be returned in the query.

About Obi Oberoi

I am Technology Aficionado who has a passion for learning, speaking, blogging and hanging out with geeks and like minded people!
This entry was posted in ORM. Bookmark the permalink.