[英]Linq query over mysql table takes too long
以下Linq Query连接6个表并创建一个'AppointmentData'列表。 在连接内部,“约会”表和“患者”表具有最大的数据。 (预约约15k,患者约5k)
执行此代码需要50秒。
IQueryable<Appointment> Appointments;
if (condition1)
{
Appointments = _context.Appointment.Where(somecondition);
}
else
{
Appointments = _context.Appointment.Where(othercondition);
}
AppointmentsData = (
from
app in Appointments
join
pat in _context.Patient
on
app.IdPatient equals pat.Id
join
doc in _context.Doctor
on
app.IdDoctor equals doc.Id
...
...
//* Around 5 more joins of the same type * //
...
select new Models.AppointmentData()
{
Id = app.Id,
Patient = pat.FullName,
Doctor = doc.FullName,
...
...
...
/* around 15 more fields from different tables
that were joined */
.....
}
).ToList();
我尝试使用较小版本的数据库,2k约会和1k病人,只需不到3秒。
我省略了一些条件,因为它们令人困惑,我确信它们与问题无关。
如果在MySQL工作台中运行生成的SQL,则可以看到执行所需的时间。 您可以在分析工作台中的查询后添加一些索引。
只需找到对于索引列可能是不错选项的列。 您可以通过为查询添加一些索引来解决此问题。
根据您的信息,我为您的挑战找到了一些解决方案。
.ToList()
吗? 意思是否真的需要一组经过评估的结果? 尝试上面的链接中描述的.AsEnumerable()
或.AsQueryable()
。 请原谅我,自从我4年前最后一次使用EF以来,我并不熟悉EF。
首先,正如其他亲爱的成员所说,您应该检查列上是否有索引,然后尝试以下代码:
IQueryable<Appointment> Appointments;
// Does not affect your slowness issue.
Appointments = condition1 ? _context.Appointment.Where(somecondition) : _context.Appointment.Where(othercondition);
AppointmentsData = Appointments
.Join(_context.Patient,
appPatientKey => appPatientKey.Id, // The primary key of Appointments.
patientKey => patientKey.Id, // The primary key of Patient.
(appPatientKey, patientKey) => new {
Appointments = appPatientKey,
Patient = patientKey
})
.Join(_context.Doctor,
appPatientKey => appPatientKey.IdDoctor, // Assuming that the IdDoctor is coming from Appointments
doctorKey => doctorKey.Id,
(appPatientKey, doctorKey) => new {
appPatientKey.Appointments,
appPatientKey.Patient,
Doctor = doctorKey
})
... // other Joins
.GroupBy(result => { AppointmentId = result.Appointments.id, PatientFullName = result.Patient.Fullname, DoctorFullName = result.Doctor.FullName...})
.Select(theEntity => new Models.AppointmentData()
{
Id = AppointmentId,
Patient = PatientFullName,
Doctor = DoctorFullName
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.