需要帮助从SQL转换为LINQ

时间:2013-02-28 17:48:04

标签: .net linq

我有以下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语句中哪里错了?谢谢。

修改:区别在于我的结果显示的顺序

2 个答案:

答案 0 :(得分: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 
                      };

BTW表名和变量名很糟糕。两个表只与下划线不同!变量boundaryID的名称看起来像某个整数(或其他标识类型)。

答案 1 :(得分:2)

一个问题是OrderByThenBy 返回有序枚举,它们不会修改基础可枚举,因此您应该使用:

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