20 Mar 2024




Intermediate

In Entity Framework Core, Select and SelectMany are LINQ methods that serve different purposes when querying data from a database.

  1. Select:

    • Select is used for picking specific properties from entities.
    • Example:

    User Class:

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public ICollection<Order> Orders { get; set; }
    }
    

    Order Class:

    public class Order
    {
        public int Id { get; set; }
        public string ProductName { get; set; }
        public decimal Price { get; set; }
    }
    

    Select:

    var result = dbContext.Users
                         .Where(u => u.Age > 18)
                         .Select(u => new { Name = u.Name, Age = u.Age });
    
    • In this example, we're selecting only the Name and Age properties from the User entity where the age is over 18.

💡 Note: EF Core Equivalent of Select in SQL is SELECT query.

SELECT Name, Age
FROM Users
WHERE Age > 18;
  1. SelectMany:

    • SelectMany combines nested collections into a single collection. It's commonly used when you have a collection containing nested collections and you want to merge them into one.
    • Example:

    User Class:

    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public ICollection<Order> Orders { get; set; }
    }
    

    Order Class:

    public class Order
    {
        public int Id { get; set; }
        public string ProductName { get; set; }
        public decimal Price { get; set; }
    }
    

    SelectMany:

    var result = dbContext.Users
                         .SelectMany(u => u.Orders);
    
    • In this example, assuming a User entity has a collection navigation property Orders, SelectMany will flatten all the Orders collections from all users into a single collection.

💡 Note: EF Core Equivalent of SelectMany in SQL is by using JOINS in SELECT query.

SELECT u.Name, o.ProductName, o.Price
FROM Users u
JOIN Orders o ON u.Id = o.UserId;

So, in essence:

  • Select is used for picking specific properties from entities.
  • SelectMany is for flattening nested collections into a single collection.
entity-framework-core
select
selectmany