views:

598

answers:

1

I'm trying to perform a simple aggregate query that returns the aggregate's result plus an extra column. This post -> http://stackoverflow.com/questions/308203/custom-query-with-castle-activerecord had a good example about how to achieve this, but I can't seem to get it to work. It seems that ActiveRecordMediator.ExecuteQuery returns an ArrayList of objects (instead of ArrayList of object[] which is what I would expect). Also if I try to cast it to ICollection I get a run-time error complaining of invalid cast. Code below, any help appreciated (don't want to use hand-written sql).

HqlBasedQuery query = new HqlBasedQuery(typeof(Something), @"select count(1),  
  p.Name from Something p 
  where p.SomeDate > :date
  order by p.Name
  group by p.Name");

query.SetParameter("date", new DateTime(2009, 1, 1));

var results = from summary in 
    (ICollection<object[]>)ActiveRecordMediator.ExecuteQuery(query)
    select new {
        Count = (int)summary[0], Name= (string)summary[1]
    };

The line after "from summary in" is the one that throws the invalid cast exception.

(Forgot to mention: using VS2008, .NET 3.5SP1, ActiveRecord 1.0RC3, NHibernate 1.2)

+1  A: 
  1. I think you meant count(*) instead of count(1) (this is why you're getting only 1-col rows)
  2. ActiveRecordMediator.ExecuteQuery (at least in RC3) returns an ArrayList (not a generic ICollection) of object[]
  3. Be careful casting count results as int. Some databases return counts as long (e.g. SQL Server)
Mauricio Scheffer
Marking you as answer since you pretty much confirmed my suspicion of being unable to cast to an ICollection (as the answer on the linked question suggested). 1) Even though it wasn't obvious to me (since it's valid SQL syntax) is that in fact count(1) was messing up my results. count(*) fixed that.2) I was browsing through AR's trunk source code and that seems to still be the case for 2.0 :/ Thanks for confirming.3) That was my bad while anonymizing the code. I already have been a victim of cast exceptions, but thanks for that as well.
enriquein

related questions