Get Row Count InvalidCast Exception from ScalarQuery
ScalarQuery<int> query = new ScalarQuery<int>(typeof(Role),
"select count(role.RoleId) from Role as role");
return query.Execute();
It crashes with an invalidcast exception, but succeeds when the counter is replaced with max.
Edit . Some databases will take a long time to return for count queries. For example, SQL Server.
ScalarQuery<long> query = new ScalarQuery<long>(typeof(Role),
"select count(r) from Role r");
return query.Execute();
Which database are you using? It could be that count doesn't return int.
You can also try using http://api.castleproject.org/html/T_Castle_ActiveRecord_Queries_CountQuery.htm
Not really an answer to the question, but a recommendation: if you want to avoid the hassle of having to issue the query at all on your own, just use ActiveRecordMediator<T>.Count()
(which has overloads that take filter criteria / strings if you want a conditional number) and everything returns int
to all databases ...
Based on testing the answers provided to date, worked for me (including where clause):
// Option 1
int result = ActiveRecordMediator<Post>.Count("BlogId = ?", blogId);
// Option 2
CountQuery query = new CountQuery(typeof(Post), "BlogId = ?", blogId);
int result = ActiveRecordMediator.ExecuteQuery(query);
// Option 3
ScalarQuery<long> query= new ScalarQuery<long>(typeof(Post),
"SELECT COUNT(*) FROM Post WHERE BlogId = ?", blogId);
long result = query.Execute();