我正在撰写一个返回batchSize
dtos的方法。我想首先使用FilterList
s来填充批次,这些Snapshot
具有一组空的相关FilterList
s。如果批次中仍有空间,我希望包含最新Snapshot
(按CreatedDateUtc
)最近的GetNeverCapturedLists()
个。{/ p>
下面的逻辑工作正常,但我想将GetLeastRecentlyCapturedLists()
和public class FilterList
{
public int Id { get; set; }
public ICollection<Snapshot> Snapshots { get; set; }
...
}
public class Snapshot
{
public int Id { get; set; }
public DateTime CreatedDateUtc { get; set; }
public int FilterListId { get; set; }
public FilterList FilterList { get; set; }
...
}
//TODO: combine queries into single query
private async Task<IEnumerable<FilterListViewUrlDto>> GetNextListsToCapture(int batchSize)
{
var neverCapturedLists = await GetNeverCapturedLists(batchSize);
if (neverCapturedLists.Count >= batchSize)
return neverCapturedLists;
var leastRecentlyCapturedLists = await GetLeastRecentlyCapturedLists(batchSize - neverCapturedLists.Count);
return neverCapturedLists.Concat(leastRecentlyCapturedLists);
}
private async Task<List<FilterListViewUrlDto>> GetNeverCapturedLists(int batchSize)
{
return await dbContext.FilterLists
.Where(x => x.Snapshots.Count == 0)
.Take(batchSize)
.ProjectTo<FilterListViewUrlDto>()
.ToListAsync();
}
private async Task<List<FilterListViewUrlDto>> GetLeastRecentlyCapturedLists(int batchSize)
{
return await dbContext.Snapshots
.GroupBy(x => x.FilterList)
.Select(x => x.OrderByDescending(y => y.CreatedDateUtc).First())
.OrderBy(x => x.CreatedDateUtc)
.Select(x => x.FilterList)
.Take(batchSize)
.ProjectTo<FilterListViewUrlDto>()
.ToListAsync();
}
合并到一个EF LINQ查询中。这样可以避免额外的数据库往返。
有办法吗?
[ ]
答案 0 :(得分:1)
我认为你需要这样的东西:
var res = await dbContext
.FilterLists
.OrderBy(q => q.Snapshots.Any())
.ThenBy(q => q.Snapshots
.Select(w => w.CreatedDateUtc)
.OrderByDescending(e => e).FirstOrDefault())
.Take(batchSize)
.ProjectTo<FilterListViewUrlDto>()
.ToListAsync();