C#Sql CTE查询 - 选择额外信息

时间:2013-02-05 19:32:23

标签: c# sql sql-server-2008 common-table-expression

我正在尝试编写CTE递归查询以构建具有'marketGroupID'(该元素的ID)和'parentGroupID'(元素的父ID)的平面表的树关系。每个'marketGroup'可以有任意数量的子市场组等等。

这是我的工作查询(在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

此查询以正确的顺序正确列出元素,而Level参数用于从元素构建树。

将其转换为C#是我遇到问题的地方。我已经集成了这个数据库,所有相应的表都是从我的数据库自动构建到我的代码中的。我尝试使用C#调用此查询,如下所示:

    EveOnlineClassesDataContext context = new EveOnlineClassesDataContext();
    IEnumerable<invMarketGroup> results = context.ExecuteQuery<invMarketGroup>
            (@"**ABOVE QUERY**");

'invMarketGroup'类是由O / R Designer构建的自动创建的类。我的问题是我无法访问每个'marketGroup'的Level参数,因为它不是表本身的一部分,并且在提供的类中没有元素。

我想从查询中检索实际的'invMarketGroup'类对象以及每个对应的级别,这样我就可以在内存中构建一个表示此结构的树。我该怎么做呢?

由于

1 个答案:

答案 0 :(得分:1)

使用该查询可能更容易在数据库中创建View vwInvMarketGroup

CREATE VIEW vwInvMarketGroup AS
    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
GO

然后你可以使用它:

IEnumerable<invMarketGroup> results = context.ExecuteQuery<invMarketGroup>(@"SELECT * FROM vwInvMarketGroup");