I try to convert the following SQL Select statement in Linq2SQL:
SELECT stoptimes.stopid,
trips.tripid,
stoptimes.sequence
FROM trips
INNER JOIN stoptimes
ON stoptimes.tripid = trips.tripid
WHERE ( trips.routeid = '3' )
AND ( trips.endplace = 'END001' )
ORDER BY stoptimes.sequence DESC
It works well but with linq2sql, I get an exception with this following statement:
var first = (from tableTrip in db.Trips
join tableStopTimes in db.StopTimes on tableTrip.TripId equals tableStopTimes.TripId
where tableTrip.RouteId == 3 && tableTrip.EndPlace == "TAEND"
select new
{
tableStopTimes.StopId,
tableStopTimes.Radius,
tableStopTimes.PlaceName,
tableStopTimes.Place,
tableStopTimes.Sequence
}).OrderByDescending(X => X.Sequence).First();
Thanks
The error “Sequence contains no elements” is a result of the collection that you are calling First() on not having anything in it.
You can call FirstOrDefault instead to avoid this issue.
EDIT:
I believe in the case of the anonymous type that you are creating, the default will be null.