views:

352

answers:

4
ScalarQuery<int> query = new ScalarQuery<int>(typeof(Role), 
                         "select count(role.RoleId) from Role as role");
return query.Execute();

It fails with the invalidcast exception but succeeds when count is replaced with max.

+1  A: 

Edit: Some databases will return long for count queries. For example SQL Server.

ScalarQuery<long> query = new ScalarQuery<long>(typeof(Role), 
                          "select count(r) from Role r");
return query.Execute();
gcores
Tried but still fails. Anyway thanks.
suhair
Have you tried with long?
gcores
A: 

What database are you using? Could be that count does not return an int.

Your could also try using http://api.castleproject.org/html/T_Castle_ActiveRecord_Queries_CountQuery.htm

Jonas Elfström
A: 

Not exactly the answer to the question, but a recommendation: if you want to avoid the hassle of having to issue a query at all yourself, then just use ActiveRecordMediator<T>.Count() (which has overloads that take criteria / filter strings if you want a conditional count) and all return int against all databases.

DotNetGuy
A: 

Based on testing the answers given to date, the following worked for me (including a 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();
Michael Maddox

related questions