LINQ with EF Core

LINQ with EF Core:

LINQ is used for querying data, filtering, projecting, joining, and aggregating data in a strongly typed manner. EF Core translates LINQ queries to optimized SQL for efficient database interactions.


1. Filtering Data Based on Conditions

Scenario: Retrieve a list of products with a price greater than 100. 

When you need to filter data based on specific conditions (e.g., price), use the Where clause in LINQ:

Example:

var expensiveProducts = dbContext.Products
                                 .Where(p => p.Price > 100)
                                 .ToList();

Use this approach to retrieve items meeting specific criteria (like filtering products based on price).


2. Projecting Data into a Custom Data Object (DTO)

Scenario: Create a custom data object (DTO) containing product names and prices. 

Use Select when you only need a subset of fields or want to transform data for a specific use case (e.g., sending a lighter data response to a client):

Example:

var productNames = dbContext.Products
                           .Select(p => new { p.Name, p.Price })
                           .ToList();

This allows you to return only the fields you need, which can improve performance by reducing data transfer.


3. Joining Multiple Tables

Scenario: Retrieve a list of products with their category names.

Use join when you need to combine data from multiple related tables:

Example:

var productCategories = from p in dbContext.Products
                        join c in dbContext.Categories on p.CategoryId equals c.Id
                        select new { p.Name, c.Name };

This is useful when you need to merge data from two or more tables (e.g., products with their category information).


4. Grouping and Aggregation

Scenario: Find the total sales revenue for each product category.

Use GroupBy for grouping data and performing aggregation:

Example:

var categoryRevenue = dbContext.Sales
                              .GroupBy(s => s.Product.Category)
                              .Select(g => new 
                              {
                                  Category = g.Key.Name,
                                  TotalRevenue = g.Sum(s => s.Amount)
                              }).ToList();

This is useful for calculating sums, averages, or other aggregates grouped by a specific attribute (e.g., revenue by category).


5. Sorting and Pagination

Scenario: Retrieve the top 5 best-selling products.

Use OrderBy and Take to sort and limit results:

Example:

var topSellingProducts = dbContext.Products
                                 .OrderByDescending(p => p.Sales)
                                 .Take(5)
                                 .ToList();

When you need to sort data by a specific field and possibly limit the number of items retrieved, sorting and pagination help with performance and UI display.


6. Complex Filtering

Scenario: Retrieve products that are either expensive (price > 100) or have high sales (sales > 500).

Use logical operators (||, &&) to apply multiple filters:

Example:

var filteredProducts = dbContext.Products
                               .Where(p => p.Price > 100 || p.Sales > 500)
                               .ToList();

This approach is ideal when filtering data with multiple conditions (e.g., filtering by either price or sales).


7. Efficient Aggregation on Large Datasets

Scenario: Calculate the average order value across all orders.

Use aggregation methods like Average to compute summary data:

Example:

var avgOrderValue = dbContext.Orders
                             .Average(o => o.TotalAmount);

Aggregation functions like Average, Sum, Min, and Max are efficient for summarizing large datasets.


8. Distinct Results

Scenario: Retrieve a list of unique customer IDs who made purchases.

Use Distinct when you need to eliminate duplicate values from your result set:

Example:

var uniqueCustomers = dbContext.Orders
                               .Select(o => o.CustomerId)
                               .Distinct()
                               .ToList();

This is useful when you need only unique values, like unique customers or product IDs.


9. Handling Null Values

Scenario: Find products that have not been assigned a category.

Use Where to filter for null values, particularly useful for cases where foreign key relationships are optional:

Example:

var unassignedProducts = dbContext.Products
                                  .Where(p => p.Category == null)
                                  .ToList();

This is helpful for finding records where a related entity is missing or has a null value.


10. Filtering with Navigation Properties

Scenario: Retrieve all products that belong to a specific category.

Use navigation properties to filter based on related entities:

Example:

var electronicsProducts = dbContext.Products
                                   .Where(p => p.Category.Name == "Electronics")
                                   .ToList();

When working with related entities (e.g., a product and its category), navigation properties allow you to filter data based on relationships.


Summary:

Filtering: Use Where for conditions.

Projections: Use Select to return specific fields or shapes.

Joins: Use join to combine data from multiple tables.

Grouping & Aggregation: Use GroupBy and aggregation functions (Sum, Average, etc.).

Sorting & Pagination: Use OrderBy, Take, Skip for sorting and limiting data.

Null Handling: Filter null values when needed.

Navigation Filtering: Filter by properties of related entities.

Distinct: Ensure unique results.


EF Core with LINQ enables you to write complex, readable, and maintainable queries that EF Core efficiently converts into SQL, allowing for powerful database access.


Summary:

LINQ with EF Core is used for filtering, projecting, joining, grouping, sorting, and aggregating data.

It enables strongly-typed queries and allows developers to write complex queries in a readable and maintainable way while EF Core translates them to SQL for efficient database access.

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced