繁体   English   中英

复杂查询LINQ Lambda

[英]Complex Query LINQ Lambda

我正在尝试在单个查询中提取数据。 由于它涉及许多表,因此我有点滞留在分组部分。

我没有足够的声誉来发布我的桌子设计的图像。 所以,我给PK,FK

 Sector (SectorId)
 Device (DeviceId:PK, CategoryId:FK)
 Ratio (SectorId,DeviceId)
 Use (UseId)
 DeviceUse (SectorId,DeviceId,UseId)
 Family (FamilyId)
 Category (CategoryId)
 Level (LevelId)
 Age(AgeId)
 Consu (SectorId,DeviceId,LevelId)
 DistributionOne (SectorId,DeviceId,LevelId)
 DistributionTwo (SectorId,DeviceId,LevelId, AgeId)

我想要实现的是:

给定一个sectorId ,从给定的所有表中检索所有相关信息。

结果将是:

所有Devices

Family分组

Category分组

和所有Ratios (对于给定的sectorIddeviceId

以及所有DeviceUses (用于相关的sectorIddeviceId )以及与之相关的Use用于deviceId

和所有Consu (相关deviceIdlevelIdageId )和相关的AgeLevel

以及所有DistributionOne (用于相关的deviceIdlevelIdsectorId )和相关的Level

以及所有DistributionTwo (用于相关的deviceIdlevelIdsectorIdageId )以及相关的AgeLevel

到目前为止,我有如下方法。

public IEnumerable<UserConfig> GetDeviceType(int sectorId)
    {
        var t = repo.GetAll().AsQueryable()                
            .Select(
            c => new UserConfig
            {
                Device = new Device { Name = c.Name, Id = c.Id },
                DistributionOne = c.DistributionOne.Where(d => d.SectorId == sectorId && d.DeviceId == c.Id).ToList(),
                DistributionTwo = c.DistributionTwo.Where(d => d.SectorId == sectorId && d.DeviceId == c.Id).ToList(),
                Consu = c.Consu.Where(d=>d.DeviceId == c.Id).ToList(),
                Category = c.Category,
                Family = c.Category.Family,
                DeviceUse = c.DeviceUse.Where(d => d.SectorId == sectorId && d.DeviceId == c.Id).ToList(),
                Ratios = c.Ratios.Where(d => d.SectorId == sectorId && d.DeviceId == c.Id).ToList(),
                Use = c.DeviceUse.Where(d=>d.DeviceId==c.Id && d.SectorId==sectorId).Select(u=>u.Use).FirstOrDefault()
            });       

        var devices = t.ToList();
        return devices;
    }

其中repoDevice的存储库

GetAll是获取Devices集的存储库方法。

我的问题:

  • 我做对了吗?

  • 如果是,那么如何将数据分组以获取嵌套的

家庭
- >分类
--->设备
DistributionOne
DistributionTwo
..等等

  • 如果不是,那么我需要纠正什么(我的表设计?,查询?)

使用GroupBy运算符:

var t = repo.GetAll().AsQueryable()
.GroupBy(c => c.Category.Family.ID)
.Select(g => new {
    FamilyID = g.Key,
    DevicesByCategory = g.GroupBy(c => c.Category.ID)
        .Select(g2 => new {
            CategoryID = g2.Key,
            Devices = g2.Select(c => new UserConfigs {
                ....
        })
   })
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM