Entity Framework ThenInclude 从原始数据集过滤

Entity Framework ThenInclude filtered from original dataset

我有一个查询,我的 ThenInclude Where 需要访问原始数据集中的数据,例如

var bikes = context.Bikes
.Include(bike => bikes.Models)
.ThenInclude(model => model.Spec.Where(spec=> spec.SpecYear == bike.YearCreated ))   
.ToList();

我目前在两个单独的查询中有这个,但如果我在数据库上完成这个请求会节省很多时间。

尝试使用投影代替Include:

var bikes = context.Bikes
    .Select(bike = new Bike
    {
        Id = bike.Id,
        // ... other fields

        Models = bike.Models.Select(m => new Model
        {
            Id = m.Id
            // ... other fields

            Spec = m.Spec
                .Where(spec => spec.SpecYear == bike.YearCreated)
                .ToList()
        })
    })
    .ToList();