I have a table holding hierarchical data that I am querying for from my web app using NHibernate. It’s pretty straight forward
CREATE TABLE [dbo].[Relationships](
[RelationshipId] [uniqueidentifier] NOT NULL,
[ParentId] [uniqueidentifier] NULL,
[ParentTypeId] [uniqueidentifier] NULL,
[ChildId] [uniqueidentifier] NOT NULL,
[ChildTypeId] [uniqueidentifier] NOT NULL
)
Now to query information from this table I’m using a feature of SQL Server (since 2005) called Common Table Expressions, or CTE for short. It lets me write recursive queries which are extremely useful for table like the one above.
WITH Ancestors(RelationshipId, ParentId, ChildId)
AS
(
SELECT r.RelationshipId, r.ParentId, r.ChildId
FROM Relationships r
WHERE ChildId = :objectId
UNION ALL
SELECT r.RelationshipId, r.ParentId, r.ChildId
FROM Relationships r
INNER JOIN Ancestors
ON Ancestors.ParentId = r.ChildId
)
SELECT RelationshipId, ParentId, ChildId FROM Ancestors
Now, this is great and the performance isn’t that bad but it can be taxing when I try to use this to determine ancestors going up the tree, or worse, using a similar query to determine decendants.
Now I’d like to simply cache the results from this query but I’m getting an error from nHibernate Index was outside the bounds of the array. if I have .SetCacheable(true). If I remove the cache support the query works fine.
The query works fine if I remove the caching support from my call to Session.CreateSQLQuery() Now I’ve looked online to try and find a cause but I haven’t found a consensus amongst the results I found.
So while I am curios why it doesn’t work, I’m more interested in finding a workaround to get caching to work with my CTE in nHibernate?
Ended up simply doing the following. I haven’t tested the caching yet but I may have to sacrifices that in favor of the flexibility the CTE provides.