toptensoftware/PetaPoco — Issue #99: Helper method "Count<T>()" easily added
Author: genez
Created: 2012-02-19 10:53:20+00:00
State: open

I think it would be easy to implement a Count() method and it would be helpful - here is my code, tested and working

public int Count(string sql, params object[] args)
{
if (EnableAutoSelect)
sql = AddSelectClause(sql);

// Split the SQL into the bits we need
string sqlSelectRemoved, sqlOrderBy, sqlCount;
if (!SplitSqlForPaging(sql, out sqlCount, out sqlSelectRemoved, out sqlOrderBy))
throw new Exception("Unable to parse SQL statement for count query");

OpenSharedConnection();
try
{
using (var cmd = CreateCommand(_sharedConnection, sqlCount, args))
{
int count = 0;

try
{
count = (int)cmd.ExecuteScalar();
OnExecutedCommand(cmd);
}
catch (Exception x)
{
OnException(x);
throw;
}

return count;
}
}
finally
{
CloseSharedConnection();
}
}

public int Count(PetaPoco.Sql sql)
{
return Count(sql.SQL, sql.Arguments);
}