I am trying to write a CTE Recursive Query to build a tree relationship of a flat table with a ‘marketGroupID’ (that element’s ID) and a ‘parentGroupID’ (the element’s parent ID). Where each ‘marketGroup’ can have any number of children ‘marketGroups’ and so on.
Here is my working query (tested in Sql Server Management):
With cte As
(SELECT [marketGroupID]
,[parentGroupID]
,[marketGroupName]
,[description]
,[iconID]
,[hasTypes]
, 0 As Level
FROM [Eve_Retribution_1.0.7].[dbo].[invMarketGroups]
WHERE [parentGroupID] IS NULL
UNION All
Select mg.marketGroupID
,mg.parentGroupID
,mg.marketGroupName
,mg.description
,mg.iconID
,mg.hasTypes
,c.Level + 1 As Level
FROM [Eve_Retribution_1.0.7].dbo.invMarketGroups mg
Inner Join cte c On mg.parentGroupID = c.marketGroupID
WHERE mg.marketGroupID <> mg.parentGroupID
)
SELECT marketGroupID
,parentGroupID
,marketGroupName
,description
,iconID
,hasTypes
, Level
FROM cte
This Query correctly lists the Elements in the correct order and the Level parameter is meant to be used to build the tree from the elements.
Translating this into C# is where I have a problem. I have integrated this database and all the corresponding tables have been built from my database into my code automatically. I try to call this query with C# as follows:
EveOnlineClassesDataContext context = new EveOnlineClassesDataContext();
IEnumerable<invMarketGroup> results = context.ExecuteQuery<invMarketGroup>
(@"**ABOVE QUERY**");
Where the ‘invMarketGroup’ class is the automatically created class built by the O/R Designer. My problem is that I lose access to the Level parameter for each ‘marketGroup’ as it was not part of the table itself and has no element in the provided class.
I want to retrieve from the query the actual ‘invMarketGroup’ class objects and the level corresponding to each so I can build a tree from this in memory representing this structure. How would I go about doing this?
Thanks
Might be easier to create a View
vwInvMarketGroupinside your database using that query:Then you can use this: