EF Core Select

Summary: in this tutorial, you will learn how to select data from a single table in EF Core using the LINQ Select() method.

We’ll use the Employee entity for the demonstration. The Employee entity maps to the Employees table in the database:

Selecting all rows from a table

To select all rows from the Employees table, you use the Employees DbSet and call the ToList() method. For example:

using static System.Console;
using HR;


using var context = new HRContext();
var employees = context.Employees.ToList();

foreach (var e in employees)
{
    WriteLine($"{e.FirstName} {e.LastName}");
}Code language: C# (cs)

Output:

John Doe
Jane Smith
Michael Johnson
Emily Brown
William Taylor
...Code language: C# (cs)

Behind the scenes, EF Cores executes the following SQL statement to get all rows and columns from the Employees table:

SELECT 
  [e].[Id], 
  [e].[DepartmentId], 
  [e].[FirstName], 
  [e].[JoinedDate], 
  [e].[LastName], 
  [e].[Salary] 
FROM 
  [Employees] AS [e]Code language: C# (cs)

Selecting some columns from a table

To get only the first name and last name and returns a list of strings, you can also use the LINQ Select() method. For example:

using static System.Console;
using HR;


using var context = new HRContext();

var names = context.Employees
                    .Select(e => $"{e.FirstName} {e.LastName}")
                    .ToList();

foreach (var name in names)
{
    WriteLine(name);
}Code language: C# (cs)

Output:

John Doe
Jane Smith
Michael Johnson
Emily Brown
William Taylor
...Code language: C# (cs)

In this example, EF Core generates a SQL that selects only the FirstName and LastName columns of the Employees table, concatenates the FirstName and LastName, and returns a list of strings.

SELECT 
  [e].[FirstName], 
  [e].[LastName] 
FROM 
  [Employees] AS [e]Code language: C# (cs)

Returning a list of anonymous objects

The following example uses the Select() method to select the FirstName and JoinedDate columns of the Employees table and returns a list of anonymous objects, where each contains the FirstName and JoinedDate properties:

using static System.Console;
using HR;


using var context = new HRContext();

var list = context.Employees
                    .Select(e => new
                    {
                        e.FirstName,
                        e.JoinedDate
                    })
                    .ToList();

foreach (var e in list)
{
    WriteLine($"{e.FirstName} - {e.JoinedDate.ToShortDateString()}");
}Code language: C# (cs)

Output:

John - 1/15/2023
Jane - 2/10/2023
Michael - 3/5/2023
Emily - 4/20/2023
William - 5/3/2023
...Code language: C# (cs)

In this example, EF Core generates an SQL that selects only the FirstName and JoinedDate from the Employees table:

SELECT 
  [e].[FirstName], 
  [e].[JoinedDate] 
FROM 
  [Employees] AS [e]Code language: C# (cs)

Summary

  • Use LINQ Select() method to select one or more columns in a table.
Was this tutorial helpful ?