meh*_*dvd 3 c# linq entity-framework ef-core-2.1
我想加载 10 个最新产品,其中包含 5 个 A 类和 5 个 B 类。因此结果包含 5 个 A 类最新产品和 5 个 B 类最新产品。
通常我可以使用这两个来做到这一点:
var listA = await (
from p in db.Set<Product>()
where p.Category == "A"
orderby p.ProductDate descending
select p
).Take(5).ToListAsync();
var listB = await (
from p in db.Set<Product>()
where p.Category == "B"
orderby p.ProductDate descending
select p
).Take(5).ToListAsync();
var result = listA.Concat(listB);
Run Code Online (Sandbox Code Playgroud)
但是正如您所看到的,这段代码需要对数据库进行 2 次调用。
我怎样才能得到结果,只使用 1 个数据库调用?
使用 EF Core 3.0.0-preview7.19362.6,您可以像这样编写它,它只生成一个查询并且运行良好:
IQueryable<Product> topA = context.Products
.Where(p => p.Category == "A")
.OrderByDescending(x => x.ProductDate)
.Take(5);
IQueryable<Product> topB = context.Products
.Where(p => p.Category == "B")
.OrderByDescending(x => x.ProductDate)
.Take(5);
List<Product> result = await topA
.Concat(topB)
.OrderBy(p => p.Category)
.ToListAsync();
Run Code Online (Sandbox Code Playgroud)