I'm trying to perform a left outer join on two tables based on the model on the picture
I'm using the following linq query:
var query = from u in Context.Set<CpcUnidadProceso>()
join p in Context.Set<CpcParadasPrevistasUnidad>()
on u.IdCpcUnidadesProceso equals p.IdCpcUnidadesProceso
into g
from result in g.DefaultIfEmpty()
where u.RefineriaArea.IdTipoArea == filters.IdTipoArea &&
(result.FechaParada >= filters.Fecha || result == null) && (result.FechaArranque <= filters.Fecha || result == null)
select
new CpcPrevisionParadasUnidadesDto
{
IdCpcUnidadesProceso = u.IdCpcUnidadesProceso,
CodigoUnidadProceso = u.CodUnidadProceso,
DescripcionUnidadProceso = u.Nombre,
IdCpcPrevisionParadasUnidadesDto = result == null ? 0 : result.IdCpcParadasPrevistasUnidades,
FechaParada = result == null ? null : result.FechaParada,
FechaArranque = result == null ? null : result.FechaArranque,
Observaciones = result == null ? null : result.Observaciones
};
But the results are not as expected, it's not returning results when there is a record with FechaParada and/or FechaArranque not null. What am I doing wrong here?
I suspect the problem to be caused by the following where
condition:
(result.FechaParada >= filters.Fecha || result == null) && (result.FechaArranque <= filters.Fecha || result == null)
First off, it might not be essential for SQL queries, but it's always a good practice to first check the null
condition, so the above can be reduced to
(result == null || (result.FechaParada >= filters.Fecha && result.FechaArranque <= filters.Fecha))
Even better, the filtering on the right side of the left outer join
should be performed before the join (for left side or inner join
it really doesn't matter):
from u in Context.Set<CpcUnidadProceso>()
join p in Context.Set<CpcParadasPrevistasUnidad>()
.Where(x => x.FechaParada >= filters.Fecha && x.FechaArranque <= filters.Fecha)
on u.IdCpcUnidadesProceso equals p.IdCpcUnidadesProceso
into g
from result in g.DefaultIfEmpty()
where u.RefineriaArea.IdTipoArea == filters.IdTipoArea
// ...
In all the cases, you have to check if you really have a data satisfying the FechaParada >= filters.Fecha && FechaArranque <= filters.Fecha
condition.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.