sql 正常工作时 Linq 查询不工作

Linq query is not working while sql is working properly

我正在将一些 SQL 查询转换为 Linq (Entity Framework)。大多数查询都运行良好,但我遇到的问题很少。

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

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

它没有return任何记录,只有一个空数组。

尝试在连接行末尾添加 "into [an alias name]"。 之后使用该别名添加一个 from 行 之后在 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  

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

on checklist.LongKey.Substring(0, 6) equals
   codeInspectionType.InspectionTypeID.ToString()

这不等同于 SQL 查询。

不幸的是,EF 不支持字符串到数字数据的转换,因此您的尝试很好,但是当字符串值包含前导零时(如您的情况),它不起作用。

为了让它工作,你需要用零填充 codeInspectionType.InspectionTypeID.ToString() 的结果,这可以通过使用 DbFunctions.Right canonical function (similar to 来完成(至少在最新的 EF6.1.3 中)) :

on checklist.LongKey.Substring(0, 6) equals 
   DbFunctions.Right("00000" + codeInspectionType.InspectionTypeID, 6)