1

I have a System.NotSupportedException using DateTime? in Linq to Entities.

My original method looks like this:

public TransportOrderLine GetLastTransportOrderLine(bool isDriver, int? driverId, int? haulierId , DateTime date, IDatabaseContext db)
{
    var lines =
        db.Query<TransportOrderLine>()
          .Where(x => ((isDriver && x.TransportOrder.DriverId == driverId) ||
                      (!isDriver && x.TransportOrder.HaulierId == haulierId)) &&
                      x.StartDatePlanned.HasValue &&
                      EntityFunctions.TruncateTime(x.StartDatePlanned) <= date)
                      .ToList();

    return lines.OrderByDescending(x => x.TransportOrder.Sequence)
                .ThenByDescending(x => x.Sequence).LastOrDefault();
}

For some reason, I'm having an exception (NotSupportedException) when linq to entities executes the DateTime part.

TransportOrderLine.StartDatePlanned is of type DateTime?.

I also split my code like this already:

var lines = db.Query<TransportOrderLine>()
              .Where(x => ((isDriver && x.TransportOrder.DriverId == driverId) ||
                         (!isDriver && x.TransportOrder.HaulierId == haulierId)))
              .ToList(); //ok


lines = lines.Where(x => x.StartDatePlanned.HasValue).ToList(); //ok

lines = lines.Where(x => EntityFunctions.TruncateTime(x.StartDatePlanned)<= date)
             .ToList(); //error here

I also tried this:

lines = lines.Where(x => (DateTime)EntityFunctions
             .TruncateTime((DateTime)x.StartDatePlanned.Value)
             .Value <= date).ToList(); //error here

Anyone knows a solution.

Thanks for your attention :)

leppie
  • 115,091
  • 17
  • 196
  • 297
Kjell Derous
  • 502
  • 1
  • 6
  • 19

1 Answers1

0

This is my solution:

var lines =
    db.Query<TransportOrderLine>()
      .Where(x => ((isDriver && x.TransportOrder.DriverId == driverId) ||
                  (!isDriver && x.TransportOrder.HaulierId == haulierId)) &&
                  x.StartDatePlanned.HasValue)
                  .ToList().Where(x => (DateTime)x.StartDatePlanned.Value <= date);
Kjell Derous
  • 502
  • 1
  • 6
  • 19