对大量数据{lin}查询延迟结果

时间:2016-04-05 11:38:44

标签: linq linq-to-sql linq-to-entities query-performance

我有查询,我需要5分钟来执行以下查询(总记录40k)

var assetAssociatedEvents = (from mainNodes in projectNodes
     select new OrgManagementEvent
     {
         OrgAssetsAssociatedEvent = new OrgAssetsAssociatedEvent
         {
             CustomerUID = Guid.Parse(CustomerUID),
             OrgUid = Guid.Parse(mainNodes.NodeObjectUID),

             AssociatedAssetUids = (from assets in customerAssets
                                    join assetNodes in assetNodeObjects
                                    on assets.AssetID equals assetNodes.fk_AssetID
                                    where assetNodes.fk_NodeObjectID == mainNodes.NodeObjectID
                                    select assets.AssetUID).Distinct().ToList().ConvertAll(Guid.Parse).ToArray(),
             Timestamp = timeStampDetail
         }
     }).ToList();
如果我做错了任何改善表现的地方,请你纠正我。

2 个答案:

答案 0 :(得分:0)

您是否需要应用所有这些转换?当您调用ToList()时,您正在遍历整个数据集,在调用ConverAll时,您再次执行此操作,然后调用ToArray达到相同的效果。也许您可以考虑仅使用linq部分,然后使用linq查询的结果进行操作

    (from assets in customerAssets join assetNodes in assetNodeObjects on assets.AssetID equals assetNodes.fk_AssetID where assetNodes.fk_NodeObjectID ==  mainNodes.NodeObjectID select assets.AssetUID)

我认为只有这一点才能大大提高绩效。

答案 1 :(得分:0)

我认为您应该拆分查询。这样的事情应该可以提高绩效:

var allAssetUids = (from assets in customerAssets
                    join assetNodes in assetNodeObjects
                    on assets.AssetID equals assetNodes.fk_AssetID                                 
                    select assets.AssetUID)
                    .Distinct()
                    .ToList()
                    .ConvertAll(Guid.Parse);

之后再做

var assetAssociatedEvents = (from mainNodes in projectNodes
 select new OrgManagementEvent
 {
     OrgAssetsAssociatedEvent = new OrgAssetsAssociatedEvent
     {
         CustomerUID = Guid.Parse(CustomerUID),
         OrgUid = Guid.Parse(mainNodes.NodeObjectUID),    
         Timestamp = timeStampDetail
     }
 }).ToList();

重复你的事件,如

foreach(var associatedEvent in assetAssociatedEvents){
    AssociatedAssetUids = allAssetUids.Where(p => p == associatedEvent.NodeObjectID).ToArray();
}