如何在包含表达式中选择一个

本文关键字:一个 选择 包含 表达式 | 更新日期: 2023-09-27 18:33:02

我有一个这样的查询:

return db.Tanks
        .Include(i => i.FluedLevelSensor)
        .Include(i => i.WaterLevelSensor)
        .Include(i => i.GasPressureSensor)
        .Include(i => i.HudrostaticPressureSensor)
        .Include(i => i.TechnologicalMaps)
        .Include(i => i.TechnologicalGroup)
        .Include(i => i.TemperatureSensor).ThenInclude(t => t.TemperatureSensorPoints)
        .Include(i => i.Material)
        .Include(i => i.TankType)
        .Include(i => i.QualityPassports).ThenInclude(i1 => i1.ContentType)
        .Include(i=>i.CalibrationTableNew)
        .Include(i => i.TankOperations)
        .Include(i => i.TankStates).ThenInclude(i => i.State);

我怎么能这样写:

return db.Tanks
     .Include(i => i.FluedLevelSensor)
     .Include(i => i.WaterLevelSensor)
     .Include(i => i.GasPressureSensor)
     .Include(i => i.HudrostaticPressureSensor)
     .Include(i => i.TechnologicalMaps.OrderByDescending(o=>o.InsertTime).FirstOrDefault())
     .Include(i => i.TechnologicalGroup)
     .Include(i => i.TemperatureSensor).ThenInclude(t => t.TemperatureSensorPoints)
     .Include(i => i.Material)
     .Include(i => i.TankType)
     .Include(i => i.QualityPassports.OrderByDescending(o => o.SamplingDate).FirstOrDefault()).ThenInclude(i1 => i1.ContentType)
     .Include(i=>i.CalibrationTableNew)
     .Include(i => i.TankOperations.OrderByDescending(o => o.OperationStartTime).FirstOrDefault())
     .Include(i => i.TankStates.OrderByDescending(o => o.Time).FirstOrDefault()).ThenInclude(i => i.State); 

还有其他方法可以优化查询吗?

如何在包含表达式中选择一个

如果无法启用 eager 加载,则可以利用所选内容根据定义包含在内。

注意:实体框架发出的 SQL 可能相同:

return db.Tanks.Select(i => new { 
    /* single easy value */
    Material = i.Material,
    /* for collections, select again */
    TankStates = i.TankStates.OrderByDescending(s => s.Time).ToList(),
    /* ... and so on */
});