-
Notifications
You must be signed in to change notification settings - Fork 4
CRUD Counting
berkeleybross edited this page Mar 19, 2018
·
5 revisions
You can count how many entities match the search conditions by calling the Count method.
When conditions is null, then it returns how many entities are in the table. Otherwise, conditions should begin with a WHERE clause.
// Synchronous
int Count<TEntity>(string conditions = null, object parameters = null, int? commandTimeout = null);
// Asynchronous
Task<int> CountAsync<TEntity>(string conditions = null, object parameters = null, int? commandTimeout = null, CancellationToken cancellationToken = default);For convenience, there is an overload which generates the WHERE clause for you, when you are looking for an equality match. All properties defined on the conditions object will be combined with an AND clause. If the value of a property is null then the SQL generated will check for IS NULL.
// Synchronous
int Count<TEntity>(object conditions, int? commandTimeout = null);
// Asynchronous
Task<int> CountAsync<TEntity>(object conditions, int? commandTimeout = null, CancellationToken cancellationToken = default);Given the POCO class:
[Table("Users")]
public class UserEntity
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}var numUsers = database.Count<User>();
// or
numUsers = await database.CountAsync<User>();MS-SQL 2012 +
SELECT COUNT(*)
FROM [Users]PostgreSQL
SELECT COUNT(*)
FROM uservar numUsers = database.Count<User>("WHERE Age > @MinAge", new { MinAge = 18 });
// or
numUsers = await database.CountAsync<User>("WHERE Age > @MinAge", new { MinAge = 18 });MS-SQL 2012 +
SELECT COUNT(*)
FROM [Users]
WHERE Age > @MinAgePostgreSQL
SELECT COUNT(*)
FROM user
WHERE age > @MinAgevar numUsers = database.Count<User>(new { Name = (string)null, Age = 18 });
// or
var numUsers = await database.CountAsync<User>(new { Name = (string)null, Age = 18 });MS-SQL 2012 +
SELECT COUNT(*)
FROM [Users]
WHERE [Name] IS NULL AND [Age] = @AgePostgreSQL
SELECT COUNT(*)
FROM user
WHERE name IS NULL AND age = @Age