我正在将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)
答案 0 :(得分:1)
使用.Include()
时,实体框架中没有选项可以过滤正在加载的内容。
查询中对.OrderByDescending().Take()
的调用会影响Device
而不是SensorStatus.SensorData
的加载方式。
您有两个选择:
按需加载所有内容,但不要调用OrderByDescending().Take()
,因为这不是您想要的:
var devices = ctx.Device
.Include(x => x.SensorStatus)
.ThenInclude(x => x.SensorData)
.Include(x => x.SensorVisibility);
最多加载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();
}