linq中复杂查询的最佳方法

时间:2015-04-20 06:18:16

标签: c# linq

在Linq Lamda中更改以下内容的最佳方法

从位置到其基本位置,类别将是唯一的。我应该首先加载直接位置的类别。如果没有具有该名称的类别,则应加载其直接父级。我也有3级的位置。

Id  Name        Location
==========================
1   Breakfast   India 
2   Breakfast   TamilNadu 
3   Breakfast   Chennai 
4   Dinner      India 
5   Dinner      TamilNadu 
6   Lunch       Chennai 
7   Combo       TamilNadu 

(印度-1级,泰米尔纳德邦-2级,钦奈-2级) 我需要结果

3   Breakfast   Chennai
5   Dinner      TamilNadu
6   Lunch       Chennai
7   Combo       TamilNadu

我的SQL查询是:

Declare @locationId UNIQUEIDENTIFIER = '7504657E-FEE4-E411-9505-BC305BB6199F'

BEGIN
    DECLARE @Locations TABLE(Id UNIQUEIDENTIFIER,LocationLevel int)

Set NoCount On

INSERT INTO @Locations 
SELECT AccountId,0 FROM Locations WHERE id = @locationId AND AccountId is not null
UNION  
SELECT FranchiseId,1 FROM Locations WHERE id = @locationId AND FranchiseId is not null
UNION  
SELECT @locationId,2

Set NoCount Off

SELECT C.* 
FROM Categories c
Join @Locations l on c.LocationId = l.Id
WHERE c.IsDeleted = 0 
AND (c.LocationId = @locationId OR (c.IsPublished = 1 And c.Status = 1))
AND l.LocationLevel = 
(
    Select Max(l1.LocationLevel) 
    From Categories c1 
    JOIN @Locations l1 on c1.LocationId = l1.Id 
    WHERE c1.Name=c.Name AND c1.IsDeleted = 0
)
Order by C.Name
END

我目前的疑问是:

var categoryes = await CategoryRepository.GetCategoryForContext(ParentLocationIdList.Keys);

此处ParentLocationIdList包含所选位置的位置ID和级别(1 | 2 | 3)

var result = categoryes.Join(ParentLocationIdList, c => c.LocationId, l => l.Key, (c, l) => new
            {
                Category = c,
                Level = l.Value,
                Name = c.Name
            });

            categoryes = result.GroupBy(g => g.Name).Select(s => s.First(d => d.Level == s.Max(m => m.Level)).Category).ToList();

            return categoryes;

0 个答案:

没有答案