2

我有以下 SQL 语句

select RegionBoundaryID, RegionBoundary.lat, RegionBoundary.long, RegionID
from RegionBoundary join Region_Boundary on RegionBoundary.RegionBoundaryID = Region_Boundary.BoundaryID
order by RegionID, RegionBoundaryID

这是它对 LINQ 的翻译

 var context = new DataClassesRegionDataContext();
 var regionBoudaries = from boundaryID in context.Region_Boundaries
                       join boundariesDetail in context.RegionBoundaries on boundaryID.BoundaryID equals boundariesDetail.RegionBoundaryID
                       select new RegionViewModel { ID = boundariesDetail.RegionBoundaryID, Latitude = boundariesDetail.lat.Value, Longitude = boundariesDetail.@long.Value, RegionID = boundaryID.RegionID };
 regionBoudaries.OrderBy(region => region.RegionID).ThenBy(region => region.ID);

但是,我从 LINQ 得到的结果与 SQL 语句的结果不同。我在 LINQ 语句中哪里错了?谢谢你。

编辑:不同之处在于我的结果出现的顺序

4

2 回答 2

2

这应该产生相同的查询:

var context = new DataClassesRegionDataContext();
var regionBoudaries = from rb in context.Region_Boundaries
                      join b in context.RegionBoundaries 
                           on rb.BoundaryID equals b.RegionBoundaryID
                      orderby rb.RegionID, b.RegionBoundaryID // ordering here
                      select new RegionViewModel { 
                           ID = b.RegionBoundaryID, 
                           Latitude = b.lat.Value, // what if null?
                           Longitude = b.@long.Value, // what if null?
                           RegionID = rb.RegionID 
                      };

顺便说一句,表名和变量名很糟糕。仅下划线不同的两个表!变量boundaryID 的名称看起来像某个整数(或其他身份类型)。

于 2013-02-28T17:52:29.403 回答
2

一个问题是返回OrderBy有序枚举,它们不会修改底层枚举,所以你应该使用:ThenBy

var regionBoudaries = from boundaryID in context.Region_Boundaries
                       join boundariesDetail in context.RegionBoundaries on boundaryID.BoundaryID equals boundariesDetail.RegionBoundaryID
                       select new RegionViewModel { ID = boundariesDetail.RegionBoundaryID, Latitude = boundariesDetail.lat.Value, Longitude = boundariesDetail.@long.Value, RegionID = boundaryID.RegionID };
regionBoudaries = regionBoudaries.OrderBy(region => region.RegionID).ThenBy(region => region.ID);
于 2013-02-28T17:52:45.740 回答