[英]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.