使用Linq2Sql的T-SQL语句



我尝试在Linq2SQL中转换以下SQL Select语句:

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 

它工作得很好,但对于linq2sql,我得到了以下语句的异常:

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

感谢

错误"Sequence contains no elements"是由于集合中没有任何内容而调用First()的结果。

您可以调用FirstOrDefault来避免此问题。

编辑:

我相信在您创建的匿名类型的情况下,默认值将为null。

最新更新