Linq 2 Sql AssociateWith方法的替代方法

时间:2018-07-01 16:51:03

标签: c# linq-to-sql entity-framework-core

我正在将ASP.NET MVC应用程序重写为ASP.NET CORE,并且遇到了使用Linq 2 Sql AssociateWith方法的情况,对此我不确定如何正确地重写它。在.NET Core中,我现在正在使用实体框架。

Linq 2 Sql代码:

var option = new System.Data.Linq.DataLoadOptions();
option.LoadWith<Device>(e => e.SensorStatus);
option.LoadWith<Device>(e => e.SensorVisibilities);
option.AssociateWith<Device>(e => e.SensorStatus.OrderByDescending(c => c.SensorDataID).Take(1));
option.LoadWith<SensorStatus>(e => e.SensorDatas);
ctx.LoadOptions = option;

当前的EF代码,我不确定是否正确:

var devices = ctx.Device.Include(x => x.SensorStatus)
                        .ThenInclude(x => x.SensorData).OrderByDescending(x => x.SensorStatus.Select(y => y.SensorDataId)).Take(1)
                        .Include(x => x.SensorVisibility);

ps。我搜索了Stack上的帖子,但只找到一个类似的主题,那里只有一个联接。 (Entity Framework vs. AssociateWith

1 个答案:

答案 0 :(得分:1)

使用.Include()时,实体框架中没有选项可以过滤正在加载的内容。
查询中对.OrderByDescending().Take()的调用会影响Device而不是SensorStatus.SensorData的加载方式。

您有两个选择:

  1. 按需加载所有内容,但不要调用OrderByDescending().Take(),因为这不是您想要的:

    var devices = ctx.Device
        .Include(x => x.SensorStatus)
            .ThenInclude(x => x.SensorData)
        .Include(x => x.SensorVisibility);
    
  2. 最多加载SensorStatus,然后选择要加载的内容:

    var devices = ctx.Device
        .Include(x => x.SensorStatus)
        .Include(x => x.SensorVisibility);
    
    foreach (var device in devices)
    {
        device.SensorStatus.SensorData = ctx.SensorStatus
            .Where(x => x.SensorStatusId == device.SensorStatusId) // I'm assuming the name of the key here
            .OrderByDescending(x => x.SensorDataId)
            .FirstOrDefault();
    }