[Solved] Select Specific Columns From Included Table In Entity Framework Core


To select specific columns when using the include statement with Entity Framework, let's consider a scenario where we have a product table and a category table, with each product belonging to a category.

Ensure that you have the necessary Entity Framework packages installed in your project. If not, you can install them via NuGet package manager.

Let's write the code to query the database and include specific columns using Entity Framework.

using System;
using System.Linq;
using System.Data.Entity;

// Assuming you have defined your DbContext class named 'DbContext' with DbSet properties for 'Product' and 'Category'

var dbContext = new DbContext();

var productsWithCategory = dbContext.Products
                                    .Include(p => p.Category) // Include the Category table
                                    .Select(p => new
                                    {
                                        ProductId = p.ProductId,
                                        ProductName = p.ProductName,
                                        CategoryName = p.Category.CategoryName // Selecting specific columns from both Product and Category tables
                                    })
                                    .ToList();
    

In the above code:

  • We start by querying the Products table from the database.
  • We then use the Include method to eagerly load the related Category table.
  • Next, we use the Select method to specify the columns we want to retrieve and finally, we convert the result to a list.

This query will return a list of anonymous objects with only the specified columns from both the Product and Category tables.

Let's consider another scenario where we have an Employee table and a Department table, with each employee belonging to a department.

Now, let's write the code to query the database and include specific columns using Entity Framework.

using System;
using System.Linq;
using System.Data.Entity;

// Assuming you have defined your DbContext class named 'EmployeeDbContext' with DbSet properties for 'Employee' and 'Department'

var dbContext = new EmployeeDbContext();
var employeesWithDepartment = dbContext.Employees .Include(e => e.Department) // Include the Department table .Select(e => new { EmployeeId = e.EmployeeId, EmployeeName = e.EmployeeName, DepartmentName = e.Department.DepartmentName // Selecting specific columns from both Employee and Department tables }) .ToList();

In this code:

  • We start by querying the Employees table from the database then use the Include method to eagerly load the related Department table, then use the Select method to specify the columns we want to retrieve.

So this query will return a list of anonymous objects with only the specified columns from both the Employee and Department tables.