views:

94

answers:

3

So I only want the count of the results not the results themselves therefore I am using count in hql. So, below is the query

(int)  Session.CreateQuery("select count(*) from TableName where Lhs=Rhs").UniqueResult();

But it is giving me the error Specified cast is not valid..

So, can any body tell me how to cast the count to int.

Any help is very much appreciated.

A: 

The problem is in your Casting because it is returning the single result (instance that matches the query) or null. What happens if you change it the int to be nullable?

VoodooChild
Same error :(..
Bipul
do this instead:var temp = Session.CreateQuery("select count(*) from TableName where Lhs=Rhs").UniqueResult();//check the type of the temptemp.GetType();I have a feeling that it is a Long and not an int.
VoodooChild
+1  A: 

Try

Convert.ToInt32(Session.CreateQuery....);

Also verify if its really returning a count or null. This could be a possibility.

Thanks

NiK
Oh it's working, but any reason why it is not working with simple casting?
Bipul
It doesn't work because it's a `long`, not an `int`. And you don't need the Convert either; you can use `.UniqueResult<long>()`.
Diego Mijelshon
@Diego: great comment on using the type converter method, forgot it was there.
VoodooChild
I am glad that my first answer in stackoverflow has been accepted.However Diego is right. It could be a long and also he is right that you can use .UniqueResult<long>() instead of a Convert. Thanks for the pointer Diego.
NiK
+1  A: 

do this instead:

var temp = Session.CreateQuery("select count(*) from TableName where Lhs=Rhs").UniqueResult();

//check the type of the temp
temp.GetType();

I have a feeling that it is a Long and not an int.

VoodooChild
in that case try casting it to Int64
VoodooChild