简体   繁体   English

EF Core Mysql性能

[英]EF Core Mysql performance

I have Mysql database with ~1 500 000 entities. 我的Mysql数据库有约1500万个实体。 When I try to execute below statement using EF Core 1.1 and Mysql.Data.EntityFrameworkCore 7.0.7-m61 it takes about 40minutes to finish: 当我尝试使用EF Core 1.1和Mysql.Data.EntityFrameworkCore 7.0.7-m61执行以下语句时,大约需要40分钟才能完成:

var results = db.Posts
    .Include(u => u.User)
    .GroupBy(g => g.User)
    .Select(g => new { Nick = g.Key.Name, Count = g.Count() })
    .OrderByDescending(e => e.Count)
    .ToList();

On the other hand using local mysql-cli and below statement, takes around 16 seconds to complete. 另一方面,使用本地mysql-cli和below语句,大约需要16秒才能完成。

SELECT user.Name, count(*) c 
FROM post 
JOIN user ON post.UserId = user.Id 
GROUP BY user.Name 
ORDER BY c DESC

Am i doing something wrong, or EF Core performance of MySql is so terrible? 我是在做错什么,还是MySql的EF Core性能如此糟糕?

Your queries are doing different things. 您的查询正在做不同的事情。 Some issues in your LINQ-to-Entities query: LINQ到实体查询中的一些问题:

  1. You call Include(...) which will eagerly load the User for every item in db.Posts . 您调用Include(...) ,它将急切地为db.Posts每个项目加载User
  2. You call Count() for each record in each group. 您为每个组中的每个记录调用Count() This could be rewritten to count the records only once per group. 可以重写此记录以仅对每个组计数一次记录。
  3. The biggest issue is that you're only using the Name property of the User object. 最大的问题是您仅使用User对象的Name属性。 You could select just this field and find the same result. 您可以仅选择此字段并找到相同的结果。 Selecting, grouping, and returning 1.5 million strings should be a fast operation in EF. 在EF中,选择,分组和返回150万个字符串应该是一种快速的操作。

Original: 原版的:

var results = 
    db.Posts
      .Include(u => u.User)
      .GroupBy(g => g.User)
      .Select(g => new { Nick = g.Key.Name, Count = g.Count() })
      .OrderByDescending(e => e.Count)
      .ToList();

Suggestion: 建议:

var results = 
    db.Posts
      .Select(x => x.User.Name)
      .GroupBy(x => x)
      .Select(x => new { Name = x.Key, Count = x.Count() })
      .OrderByDescending(x => x.Count)
      .ToList();

If EF core still has restrictions on the types of grouping statements it allows, you could call ToList after the first Select(...) statement. 如果EF core仍然对其允许的分组语句类型有限制,则可以在第一个Select(...)语句之后调用ToList

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

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