Understanding LINQ Queries in Entity Framework Core

What is LINQ?

LINQ (Language Integrated Query) is a powerful feature in .NET that allows querying data using a syntax similar to SQL, directly in C# or other .NET languages. LINQ simplifies the process of working with data in databases, collections, XML, and other sources.

  • Readable and Expressive: Queries are written in a natural, intuitive syntax.
  • Strongly Typed: Errors can be caught at compile time.
  • Integrated: Works seamlessly with Entity Framework Core to query databases.

Simple LINQ Query Examples in EF Core

Let’s explore LINQ queries with step-by-step examples:

1. Fetch All Records


// Example: Get all customers
using (var context = new ApplicationDbContext())
{
    var customers = context.Customers.ToList();
}

                

This query retrieves all customers from the Customers table.

2. Filter Data


// Example: Get customers from a specific city
using (var context = new ApplicationDbContext())
{
    var customersInCity = context.Customers
        .Where(c => c.City == "New York")
        .ToList();
}

                

The Where method filters customers who are from "New York."

3. Select Specific Columns


// Example: Get customer names and cities
using (var context = new ApplicationDbContext())
{
    var customerDetails = context.Customers
        .Select(c => new { c.Name, c.City })
        .ToList();
}

                

The Select method is used to project specific columns (Name and City) into an anonymous type.

4. Join Two Tables


// Example: Get orders with customer names
using (var context = new ApplicationDbContext())
{
    var ordersWithCustomerNames = context.Orders
        .Join(context.Customers,
            order => order.CustomerId,
            customer => customer.Id,
            (order, customer) => new { order.Id, customer.Name, order.Total })
        .ToList();
}

                

The Join method combines data from the Orders and Customers tables using the CustomerId key.

5. Group Data


// Example: Group orders by customer
using (var context = new ApplicationDbContext())
{
    var ordersByCustomer = context.Orders
        .GroupBy(o => o.CustomerId)
        .Select(group => new
        {
            CustomerId = group.Key,
            TotalOrders = group.Count(),
            TotalAmount = group.Sum(o => o.Total)
        })
        .ToList();
}

                

This query groups orders by CustomerId and calculates the number of orders and total amount for each customer.