tags:

views:

61

answers:

1

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.

+1  A: 

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)
);
dcp
I re-wrote this again and it also worked. Thanks for the help but I was having a minor bug and don't need this in the end.
Bathan