I want to query a table with some conditions based on user input.
I have this code:
IQueryable<Turno> turnoQuery = dc.Turno;
if (helper.FechaUltimaCitaDesde != DateTime.MinValue)
{
turnoQuery = turnoQuery.Where(t => t.TurnoFecha >= helper.FechaUltimaCitaDesde);
}
if (helper.FechaUltimaCitaHasta != DateTime.MinValue)
{
turnoQuery = turnoQuery.Where(t => t.TurnoFecha <= helper.FechaUltimaCitaHasta);
}
if (helper.SoloCitasConsumidas)
{
turnoQuery = turnoQuery.Where(t => t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Consumido));
}
else if(helper.AnuladoresDeCitas)
{
turnoQuery = turnoQuery.Where(t => t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Cancelado) || t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Ausente));
}
The problem I'm having is that the "where" clause gets overwritten with the last one.
Whats the correct way to do something like this on LINQ?
The "helper" object is a custom class storing the user input dates for this example.
You could combine the expressions by using a series of ternary operations. This isn't tested so there may be some syntax issues, but here's the basic idea:
turnoQuery = turnoQuery.Where(
t => t.TurnoFecha >= helper.FechaUltimaCitaDesde != DateTime.MinValue ? helper.FechaUltimaCitaDesde : DateTime.MinValue &&
t.TurnoFecha <= helper.FechaUltimaCitaHasta != DateTime.MinValue ? helper.FechaUltimaCitaHasta : DateTime.MaxValue &&
helper.SoloCitasConsumidas ? t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Consumido :
t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Cancelado) || t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Ausente) &&
helper.FechaUltimaCitaDesde != DateTime.MinValue ? t.TurnoFecha >= helper.FechaUltimaCitaDesde : t.TurnoFecha <= helper.FechaUltimaCitaHasta &&
helper.SoloCitasConsumidas ? t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Consumido) : t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Cancelado) || t.Estado == Convert.ToInt32(EnmEstadoDelTurno.Ausente)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With