如何在include表达式中选择一个?

时间:2016-02-03 18:40:22

标签: c# entity-framework entity-framework-core

我有这样的查询:

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); 

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

1 个答案:

答案 0 :(得分:0)

如果您无法启用预先加载,则可以利用选择的任何内容定义包含

注意:实体框架发出的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 */
});