当sql正常工作时,Linq查询无效

时间:2016-06-19 12:52:46

标签: c# sql-server linq entity-framework-4

我正在将一些SQL查询转换为Linq(实体框架)。大多数查询工作正常,但我对下面的问题几乎没有任何问题。

当我在SQL Server Management Studio中尝试此查询时,它会返回多个记录。

SELECT
    bDrillDown,
    Icon
FROM 
    dbo.Checklist 
INNER JOIN 
    dbo.Codes ON Checklist.iCodeID = Codes.iCodeID 
              AND Codes.bDeleted = 0 AND Codes.bObsolete = 0
INNER JOIN 
    dbo.CodeGroup ON Codes.iGroupID = CodeGroup.iGroupID 
                  AND CodeGroup.bDeleted = 0 AND CodeGroup.bInspection = 1
INNER JOIN 
    dbo.CodeInspectionTypeV ON Cast(LEFT(Checklist.LongKey, 6) as int) = CodeInspectionTypeV.InspectionTypeID
WHERE 
    Checklist.bDeleted = 0
ORDER BY 
    iChecklistID

当我将其转换为LINQ查询时,如:

var checkList = from checklist in db.Checklists
                join code in db.Codes on checklist.iCodeID equals code.iCodeID
                where code.bDeleted == false && code.bObsolete == false
                join codeGroup in db.CodeGroups on code.iGroupID equals codeGroup.iGroupID
                where codeGroup.bDeleted == false && codeGroup.bInspection == true
                join codeInspectionType in db.CodeInspectionTypeVs on checklist.LongKey.Substring(0, 6) equals codeInspectionType.InspectionTypeID.ToString()
                where checklist.bDeleted == false
                orderby checklist.iChecklistID
                select new
                        {
                            checklist.iChecklistID,
                            InspectionTypeID = checklist.LongKey.Substring(0, 6).ToString()
                        };

它不返回任何记录,只返回一个空数组。

2 个答案:

答案 0 :(得分:3)

问题显然出现在以下连接条件

.controller('feedsctrl',['$scope','$http',function($scope,$http){
    $scope.feeds = [];
    $scope.loadmore=function() {
        var params = {};
        if($scope.feeds.length > 0) {
            params['after']=$scope.feeds[$scope.feeds.length - 1].profile_id;
            }
$http.get('http://localhost/myapp/app_ion/feeds.php').success(function(data){
       $scope.feeds=console.log(data) ;
       $scope.feeds=data;
        $scope.$broadcast('scroll.infiniteScrollComplete');

   });
   }
}])

不等同于SQL查询。

不幸的是,EF不支持字符串到数字数据转换,所以您的尝试很好,但是当字符串值包含前导零时,它不起作用。

为了使它工作,你需要使用on checklist.LongKey.Substring(0, 6) equals codeInspectionType.InspectionTypeID.ToString() 的结果保留pad,这可以通过使用DbFunctions.Right规范函数(至少在最新的EF6.1.3中)完成(类似于how to sort varchar column containing numeric values with linq lambdas to Entity):

codeInspectionType.InspectionTypeID.ToString()

答案 1 :(得分:0)

尝试在连接线的末尾添加“[别名”]。 之后使用该别名添加一行 之后在where行

中使用该别名
from checklist in db.Checklists  
join code in db.Codes on checklist.iCodeID equals code.iCodeID into Temp1
from t1 in Temp1  
where t1.bDeleted == false && t1.bObsolete == false