简体   繁体   中英

System.NotSupportedException using DateTime? in Linq to Entities

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 :)

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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM