I am using Entity Framework 6 with MySQL 5.7. I am trying to tune queries and evaluate performance problems. There is a particular query showing up in the Slow Query Log. Here is an entry:
# Time: 2021-02-10T17:28:40.313796Z
# User@Host: user @ localhost [::1] Id: 89
# Query_time: 40.252085 Lock_time: 0.000044 Rows_sent: 1 Rows_examined: 758678
SET timestamp=1612978120;
SELECT
`Project1`.`Id`,
`Project1`.`Time`,
`Project1`.`Message`,
`Project1`.`Device_Id`,
`Project1`.`Type_Id`
FROM `DeviceEvents` AS `Project1`
WHERE (`Project1`.`Device_Id` = 2) AND (`Project1`.`Type_Id` = 7)
ORDER BY
`Project1`.`Time` DESC LIMIT 1;
As you can see the query is taking over 40 seconds. If I copy this exact query in Workbench and run it, it takes 0.003 seconds. So, I am not sure what EF is doing that is affecting the execution time when it gets to MySQL. It looks like MySQL is examining a lot of rows even though there is an index on Device_Id, Type_Id, and Time.
EXPLAINof your query - both from within EF (using theDbContext.Databaseobject to execute anEXPLAIN) and from within MySQL Workbench.