简体   繁体   English

在EFCore中的单个LINQ查询中获得2个前5个

[英]Getting 2 Top 5 within a single LINQ query in EFCore

I want to load 10 latest products containing 5 of category A and 5 of category B. So the result contains 5 latest products with category A and 5 latest products of category B. 我想加载10个最新产品,其中包含5个A类和5个B类。所以结果包含5个类别A的最新产品和5个类别B的最新产品。

Normally I can do it using these two: 通常我可以用这两个来做:

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);

But as you see this piece of code requires 2 calls to the database. 但正如您所看到的那段代码需要2次调用数据库。

How can I get the result, using just 1 database call? 如何只使用1个数据库调用即可获得结果?

Use Concat before await await之前使用Concat

var listA = (
    from p in db.Set<Product>()
    where p.Category == "A"
    orderby p.ProductDate descending
    select p
).Take(5);

var listB = (
    from p in db.Set<Product>()
    where p.Category == "B"
    orderby p.ProductDate descending
    select p
).Take(5);

var result= await listA.Concat(listB).ToListAsync();

With EF Core 3.0.0-preview7.19362.6, you can write it like this which produces just a single query and works perfectly fine : 使用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();

最近,EF团队已确认 UNION,CONCAT,EXCEPT和INTERSECT的翻译将被添加到EF Core 3.所以,如果你使用的是EF Core 3 Preview,那么祝你好运,否则你必须使用RAW SQL查询你想一次性去。

In LINQ Query something like this should work: 在LINQ Query这样的东西应该工作:

 var list = await(db.Product.Where(p => p.Category == "A" || p.Category == "B").OrderByDescending(p => p.ProductDate)
                                .ToList()
                                .GroupBy(p => p.Category)
                                .SelectMany(t => t.Select(b => b).Zip(Enumerable.Range(0, 5), (j, i) => j))).ToListAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM