简体   繁体   English

EF Linq 包括最后

[英]EF Linq include last

I have 2 tables one with cities and another with temperature/date values for the cities, a city can have multiple dates with temperature.我有两张表,一张是城市,另一张是城市的温度/日期值,一个城市可以有多个温度日期。

how could I by EF + linq bring the cities + the most recent temperature of each one我怎么能通过EF + linq 带来城市+每个城市的最近温度

something like: _context.city.include(x=> x.temperature().last());类似: _context.city.include(x=> x.temperature().last());

You could achieve this by projecting the city and the last temperature to a new object, in a Select expression.您可以通过在Select表达式中将城市和最后一个温度投影到新的 object 来实现这一点。 The code snippet you included in your question is missing a few steps, so I'm going to take a guess at your data structures:您在问题中包含的代码片段缺少几个步骤,因此我将猜测您的数据结构:

await _context.Cities.Select(city => new
{
    City = city,
    LastTemperature = city.Temperatures
                         .OrderByDescending(t => t.DateRecorded)
                         .FirstOrDefault(),
}).ToListAsync();

You always should take control over which temperature is "last" by ordering them by a chosen property.您始终应该通过按所选属性对它们进行排序来控制“最后”的温度。 Doing that, it makes sense to use Take(1) in Include , for example to get the most recent one:这样做,在Include中使用Take(1)是有意义的,例如获取最新的:

_context.Cities
    .Include(x=> x.Temperatures.OrderByDescending(t => t.Date).Take(1));

Filtered/ordered Include is supported as of EF core 5 . 从 EF core 5 开始支持过滤/排序的Include

Since you're already trying something along these lines I'm assuming you're using EFC 5 or 6.由于您已经在尝试这些方面的东西,我假设您正在使用 EFC 5 或 6。

I'm not a fan of filtering includes as it leads to ambiguity (a filtered include's nav property is considered loaded so the user of the result must have knowledge of possibly encapsulated behavior).我不喜欢过滤包含,因为它会导致歧义(过滤包含的 nav 属性被认为loaded ,因此结果的用户必须了解可能封装的行为)。 I'd prefer projecting to a new/anonymous type:我更喜欢投影到新的/匿名类型:

_context.TemperatureReading
    .GroupBy( tr => tr.City )
    .Select( g => new
    {
        City = g.Key,
        LatestTemp = g.OrderByDescending( t => t.Date ).First(),
    } );

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

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