Linq查询使用另一个查询的结果

时间:2018-03-12 16:02:20

标签: entity-framework linq

我有一个以IQueryable

形式获取数据的查询
        var assys = assetrelationshipRepository.GetAll()
            .Where(x => x.AssetId == siteAssetId)
            .Where(x => x.RelationshipTypeId == (long)AssetRelationshipTypeEnum.Parent)
            .Where(x => x.RelatedAsset.AssetTypeId == (long)AssetTypeEnum.Assembly)
            .Select(x => x.RelatedAsset.CustomAssetAttributes2);

对于返回的每个'assy',我想得到它的AssetId并用它来获取'subassys'列表,见下​​文。对于每个'assy'记录,assyId变量应替换其AssetId。

        var subassys = assetrelationshipRepository.GetAll()
            .Where(x => x.AssetId == assyId)
            .Where(x => x.RelationshipTypeId == (long)AssetRelationshipTypeEnum.Parent)
            .Where(x => x.RelatedAsset.AssetTypeId == (long)AssetTypeEnum.SubAssy)
            .Select(x => x.RelatedAsset.CustomAssetAttributes2);

我认为我需要使用ForEach,有没有人知道我想做什么是可能的?

由于

1 个答案:

答案 0 :(得分:0)

应用ForEach将是一种非常糟糕的方法来检索您想要的结果。您可以为该查询应用joingroup

var assysQuery = assetrelationshipRepository.GetAll()
            .Where(x => x.AssetId == siteAssetId)
            .Where(x => x.RelationshipTypeId == (long)AssetRelationshipTypeEnum.Parent)
            .Where(x => x.RelatedAsset.AssetTypeId == (long)AssetTypeEnum.Assembly);

然后应用joingroup;

var subAssysQuery = 
            from assy in assysQuery
            join subAssy in assetrelationshipRepository.GetAll() on assy.Id equals subAssy.AssetId
            where 
            subAssy.RelationshipTypeId == (long)AssetRelationshipTypeEnum.Parent &&
            subAssy.RelatedAsset.AssetTypeId == (long)AssetTypeEnum.Assembly
            group assy by assy.Id into g
            select new
            {
              AssyId = g.Key,
              SubAssets = g.Select(x => x.RelatedAsset.CustomAssetAttributes2),
            };

对于每CustomAssetAttributes2条记录,此值应为subassys {。}}。

  

注意:另外,我建议您使用select子句的已知类型   匿名类型。