如何使用Linq C#获取层次结构

时间:2012-07-12 07:03:18

标签: linq c#-4.0

我遇到了linq c#的问题,我的数据库中有三个表 首先是tbl_ActivitiesMaster (this contain Parent Child Data)

CREATE TABLE  
tbl_ActivityMaster
(intActivityId int IDENTITY(1,1) NOT NULL,  
strActivityDesc varchar(max) NULL,  
intActivityUOMId int,
dtDatetime datetime,
IsParentActivity int,
IsAlerternateActivity int NULL,
intParentToId int NULL,
intTaskId int NULL,
intAlternateId int NULL,
CONSTRAINT PK_tbl_ActivityMaster PRIMARY KEY CLUSTERED  (   
[intActivityId] ASC )
WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS 
= ON, ALLOW_PAGE_LOCKS  = ON) 
ON [PRIMARY] ) ON [PRIMARY]

第二个是tbl_TendersTaskActivities

CREATE TABLE tbl_TendersTaskActivities(
    intID [int] IDENTITY(1,1) NOT NULL,
    intTaskId [int] NULL,
    intTenderId [int] NULL,
    intProjectWorkGroupId [int] NULL,
    intActivityId [int] NULL,
    ftActivityQty [float] NULL,
    ftActivityRate [float] NULL,
    intUomId int NULL,
    dtTaskStartDate [datetime] NULL,
    dtTaskCompletionDate [datetime] NULL,
    intFlag [int] NULL,
    IsCanceled [bit] NULL,
 CONSTRAINT [PK_tbl_TendersTask] PRIMARY KEY CLUSTERED 
(
    [intID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

我希望数据来自表tbl_TendersTaskActivities与parentvities的父级作为层次结构输出 请有人可以解决这个问题 提前谢谢。

2 个答案:

答案 0 :(得分:0)

from m in DataContext.tbl_ActivityMaster
             join d in DataContext.tbl_TendersTaskActivities on m.intActivityId equals d.intActivityId    into temp
             from t in temp.DefaultIfEmpty()
             group SysDocument by m

答案 1 :(得分:0)

在LinqToSql中,您可以使用DataLoadOptions来提取相关记录:

DataLoadOptions myOptions = new DataLoadOptions();
myOptions.LoadWith<ActivityMaster>(x => x.TendersTaskActivities);

using (CustomDataContext myDC = new CustomDataContext(connStr))
{
  myDC.LoadOptions = myOptions;

  List<ActivityMaster> masters = myDC.ActivityMasters
    .Where(filter)
    .ToList();  //TendersTaskActivities also loaded.
  return masters; 
}