嘿大家,我有一个有效的 LINQ 查询,但我想知道它是否可以进一步优化..
这就是我现在正在做的事情:
var selectionsAnimals = await this.context.SelectionAnimals
.GroupBy(a => a.AnimalId)
.ToListAsync();
var animalsSelections = selectionsAnimals
.Select(a => new AnimalsSelection
{
AnimalId = a.First().AnimalId,
SelectionIds = a.Select(b => b.SelectionId)
.OrderBy(b => b)
.ToList()
})
.ToList();
我想知道这两个 LINQ 语句是否可以合并并作为一个可等待的数据库 LINQ 查询?
这是数据库实体:
public class SelectionAnimals
{
public int Id { get; set; }
public int AnimalId { get; set; }
public int SelectionId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
这是模型:
public class AnimalsSelection
{
public int AnimalId { get; set; }
public IList<int> SelectionIds { get; set; }
}
最后我将animalsSelection映射到IEnumerable<AnimalsSelection>
(模型)
最佳答案
Michael Coxon总体来说是正确的,但是 EF Core 目前甚至在基本的查询构造处理中也相当不稳定。
因此(遗憾的是)最重要的问题是您使用的 EF Core 版本是什么。这确实是一个反复试验的过程。例如,在 EF Core 1.1.0(版本)中,Michael 的构造不起作用,但以下等效构造可以:
var animalsSelections = await db.SelectionAnimals
.GroupBy(a => a.AnimalId)
.Select(g => new AnimalsSelection
{
AnimalId = g.Key,
SelectionIds = g.OrderBy(a => a.SelectionId)
.Select(a => a.SelectionId)
.ToList()
})
.ToListAsync();
关于c# - 两个 LINQ 语句对应一个可等待的 LINQ 数据库查询(优化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40761993/