Sum in LINQ Query in Entity Framework Core

Sum method is used to used to calculate the total or sum of any numeric column in database.

using EntityFrameworkCore_ConsoleApp.Models;

namespace EntityFrameworkCore_ConsoleApp
{
    public class Program
    {
        static void Main(string[] args)
        {
            using (var databaseContext = new DatabaseContext())
            {
                var sum = (from product in databaseContext.Products
                           select product.Quantity).Sum();
                Console.WriteLine("Sum: " + sum);
            }
        }
    }
}
Sum: 146

You can use combination of Sum method and Where as below:

using EntityFrameworkCore_ConsoleApp.Models;

namespace EntityFrameworkCore_ConsoleApp
{
    public class Program
    {
        static void Main(string[] args)
        {
            using (var databaseContext = new DatabaseContext())
            {
                var sum = (from product in databaseContext.Products
                           where product.Status == true 
                           select product.Quantity).Sum();
                Console.WriteLine("Sum: " + sum);
            }
        }
    }
}
Sum: 83

You can also do the sum of an expression with multiple columns as below:

using EntityFrameworkCore_ConsoleApp.Models;

namespace EntityFrameworkCore_ConsoleApp
{
    public class Program
    {
        static void Main(string[] args)
        {
            using (var databaseContext = new DatabaseContext())
            {
                var sum = (from product in databaseContext.Products
                           where product.Status == true
                           select product).Sum(product => product.Price * product.Quantity);
                Console.WriteLine("Sum: " + sum);
            }
        }
    }
}
Sum: 1310