Skip and Take 不使用 MySQL EntityFrameworkCore

Posted

技术标签:

【中文标题】Skip and Take 不使用 MySQL EntityFrameworkCore【英文标题】:Skip and Take not working with MySQL EntityFrameworkCore 【发布时间】:2017-05-30 02:53:48 【问题描述】:

我正在尝试从 mysql db 中对 Products 进行分页,但如果我使用 Skip()Take() 它会返回一个空的 Json 数组作为我的 Web api 响应,如下所示

[]

但是FirstOrDefault()Where() 等扩展方法可以正常工作。这是sn-p的代码:

public IActionResult GetPage(int page, int pageSize = 2)
            
    int productCount = _context.Products.Count(); // 5
    float totalPages = (float)Math.Ceiling((float)productCount / pageSize); //2.5 -- round to 3

    if (page < 1 || page > totalPages) return NotFound();
    var products = _context.Products.Skip((page - 1) * pageSize).Take(pageSize); //skip & take err mysql ef

    return Ok(products);

我什至对查询.Skip(1).Take(2) 进行了硬编码,但没有运气。有人遇到过这个问题或知道解决方法吗?

【问题讨论】:

您在申请 Skip and Take 之前是否尝试过订购查询? 【参考方案1】:

原来是Oracle提供的MySql.DataEF连接器的一个bug,bug详细信息发布在here。

替代解决方案:

我改用另一个名为Pomelo 的连接器,现在SkipTake 工作得很好。您可以在 nuget 中搜索 Pomelo.EntityFrameworkCore.MySql 并为您的项目安装适当的版本。

要使用,只需在配置DbContext时将.UseMySQL改为.UseMySql,因为oracle连接器使用SQL,pomelo使用Sql,只是大小写不同。

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));

【讨论】:

【参考方案2】:

好吧,我知道答案是旧的……但是……在 EF mysql 中,您需要在跳过之前传递一个 order by 或 order by desc。

真正的解决方案,而不是替代方案:

像这样:

var yourVar = dbContext.LinkText
                       .Where(x => x.active)
                       .OrderByDescending(x => x.startDate)
                       .Skip(50)
                       .Take(10);

您可以使用任何关于跳过的逻辑并采取如下方式:

query
.OrderByDescending(x => x.startDate)
.Skip(page <= 1 ? 0 : (page - 1) * (qty == 0 ? 10 : qty))
.Take(qty == 0 ? 10 : qty);

然后 mySQL 将收到代码:

*...the query...*     
ORDER BY  `Extent1`.`startDate` DESC 
     LIMIT 0,10

【讨论】:

以上是关于Skip and Take 不使用 MySQL EntityFrameworkCore的主要内容,如果未能解决你的问题,请参考以下文章