Consulta LINQ lenta – Agrupación anidada y ToList()
Tengo la siguiente consulta de Linq que tarda 10 segundos o más en ejecutarse – ¿hay una mejor manera de escribirla? Funciona, pero es muy lenta:
var searchQuery = (from p in db.Property
where p.PropertyVendorId == loggedInUserId
from aues in db.ApplicationUserEvents
where aues.ApplicationUserEventsPropertyId == p.PropertyId
&& aues.ApplicationUserEventsFeedbackDate != null
group p by new { p.PropertyId, p.PropertyAddress1, p.PropertyAddress2, p.PropertyAddress3, p.PropertyZipOrPostcode } into pg
select new DashboardFeedback
{
PropertyNumber = pg.FirstOrDefault().PropertyNumber,
PropertyId = pg.FirstOrDefault().PropertyId,
PropertyReference = pg.FirstOrDefault().PropertyId,
PropertyAddress1 = pg.FirstOrDefault().PropertyAddress1,
PropertyAddress2 = pg.FirstOrDefault().PropertyAddress2,
PropertyZipOrPostcode = pg.FirstOrDefault().PropertyZipOrPostcode,
DashboardFeedbackChart = (
from aues2 in db.ApplicationUserEvents
where aues2.ApplicationUserEventsPropertyId == pg.FirstOrDefault().PropertyId
&& aues2.ApplicationUserEventsFeedbackDate != null
from fos in db.FeedbackOptions
where fos.FeedbackOptionsApplicationUserEventsId == aues2.ApplicationUserEventsId
from fo in db.FeedbackOption
where fos.FeedbackOptionsFeedbackOptionId == fo.FeedbackOptionId
group fo by new { fo.FeedbackOptionName, aues2.ApplicationUserEventsPropertyId } into g
select new DashboardFeedbackChart
{
FeedbackOptionName = g.FirstOrDefault().FeedbackOptionName,
FeedbackOptionNameCount = g.Count()
}).ToList<DashboardFeedbackChart>()
}).ToList();
- Una propiedad tiene muchos eventos de usuario de aplicación.
- Un evento de usuario de aplicación tiene muchas opciones de retroalimentación.
- Una opción de retroalimentación tiene una opción de retroalimentación.
¡Gracias por cualquier consejo!
davy.ai
Una manera de mejorar el rendimiento de esta consulta LINQ es utilizar operaciones join en lugar de múltiples cláusulas from. Las operaciones join ayudan a reducir el número de registros procesados y mejorar la eficiencia de la consulta.
Así es como se podría reescribir la consulta usando operaciones join:
En esta consulta reescrita, la primera operación join vincula las tablas Property y ApplicationUserEvents, mientras que la segunda operación join vincula las tablas ApplicationUserEvents, FeedbackOptions y FeedbackOption. Las condiciones where se combinan para cada cláusula join, y los registros resultantes se agrupan como en la consulta original.
Esta consulta puede funcionar mejor que la original, pero es importante probarla y ajustarla según el esquema y los datos específicos de la base de datos. Las optimizaciones adicionales podrían incluir el uso de índices, el almacenamiento en caché o la paginación de los resultados.