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 = databaseContext.Products.Sum(product => product.Quantity);
Console.WriteLine("Sum: " + sum);
}
}
}
}
Output
Sum: 146
You can use combination of Sum method and Where method as below:
using EntityFrameworkCore_ConsoleApp.Models;
namespace EntityFrameworkCore_ConsoleApp
{
public class Program
{
static void Main(string[] args)
{
using (var databaseContext = new DatabaseContext())
{
var sum = databaseContext.Products.Where(product => product.Status == true).Sum(product => product.Quantity);
Console.WriteLine("Sum: " + sum);
}
}
}
}
Output
Sum: 83
You can use combination of Sum method and Where method and Select method as below:
using EntityFrameworkCore_ConsoleApp.Models;
namespace EntityFrameworkCore_ConsoleApp
{
public class Program
{
static void Main(string[] args)
{
using (var databaseContext = new DatabaseContext())
{
var sum = databaseContext.Products.Where(product => product.Status == true).Select(product => product.Quantity).Sum();
Console.WriteLine("Sum: " + sum);
}
}
}
}
Output
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 = databaseContext.Products.Where(product => product.Status == true).Sum(product => product.Price * product.Quantity);
Console.WriteLine("Sum: " + sum);
}
}
}
}
Output
Sum: 1310