Count method is used to return the number of elements present in the collection or the number of elements that have satisfied a given condition.
using EntityFrameworkCore_ConsoleApp.Models;
namespace EntityFrameworkCore_ConsoleApp
{
public class Program
{
static void Main(string[] args)
{
using (var databaseContext = new DatabaseContext())
{
var count = databaseContext.Products.Count();
Console.WriteLine("Count: " + count);
}
}
}
}
Output
Count: 8
You can add condition to Count method as below:
using EntityFrameworkCore_ConsoleApp.Models;
namespace EntityFrameworkCore_ConsoleApp
{
public class Program
{
static void Main(string[] args)
{
using (var databaseContext = new DatabaseContext())
{
var count1 = databaseContext.Products.Count(product => product.Status == true);
Console.WriteLine("Count 1: " + count1);
var count2 = databaseContext.Products.Count(product => product.Price >= 5 && product.Price <= 10);
Console.WriteLine("Count 2: " + count2);
}
}
}
}
Output
Count 1: 4
Count 2: 2
You can use combination of Count 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 count = databaseContext.Products.Where(product => product.Status == true).Count();
Console.WriteLine("Count: " + count);
}
}
}
}
Output
Count: 4