Average method is used to calculate the average 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 average = databaseContext.Products.Average(product => product.Price);
Console.WriteLine("Average: " + average);
}
}
}
}
Output
Average: 16.625
You can use combination of Average 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 average = databaseContext.Products.Where(product => product.Status == true).Average(product => product.Price);
Console.WriteLine("Average: " + average);
}
}
}
}
Output
Average: 15.25
You can use combination of Average 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 average = databaseContext.Products.Where(product => product.Status == true).Select(product => product.Price).Average();
Console.WriteLine("Average: " + average);
}
}
}
}
Output
Average: 15.25