我有一个SQL查询:
SELECT Sum(ABS([Minimum Installment])) AS SumOfMonthlyPayments FROM tblAccount
INNER JOIN tblAccountOwner ON tblAccount.[Creditor Registry ID] = tblAccountOwner.
[Creditor Registry ID] AND tblAccount.[Account No] = tblAccountOwner.[Account No]
WHERE (tblAccountOwner.[Account Owner Registry ID] = 731752693037116688)
AND (tblAccount.[Account Type] NOT IN ('CA00', 'CA01', 'CA03', 'CA04', 'CA02', 'PA00', 'PA01', 'PA02', 'PA03', 'PA04'))
AND (DATEDIFF(mm, tblAccount.[State Change Date], GETDATE()) <=
6 OR tblAccount.[State Change Date] IS NULL)
AND (tblAccount.[Account Status ID] <> 999)
AND ((tblAccount.[Account Type] NOT IN ('CL01','PL01','CL10','
CL11','PL10','PL11','OD','CL00','PL00','CL03','CL20','CL30','CL31','CL32',
'CL33','CL34','CL35','CL69','CL90','ML00','PL03','PL20','PL30','PL31','PL33',
'CA00', 'CA01', 'CA03', 'CA04', 'CA02', 'PA00', 'PA01', 'PA02', 'PA03', 'PA04',
'PL34','PL35','PL40','PL90'))
AND NOT CONTAINS(tblAccount.[Account Type], 'Overdra')
OR NOT CONTAINS(tblAccount.[Account Type], 'Mortgage')
OR NOT CONTAINS(tblAccount.[Account Type],'Revolv')
OR NOT CONTAINS(tblAccount.[Account Type],'*Credit*Card*'))
我已将其翻译为LINQ:
var excludeTypes = new[]
{
"CA00", "CA01", "CA03", "CA04", "CA02",
"PA00", "PA01", "PA02", "PA03", "PA04"
};
var maxStateChangeMonth = 4;
var excludeStatusId = 999;
var includOtherPayments = new[] {
"CL01","PL01","CL10",
"CL11","PL10","PL11","OD","CL00","PL00","CL03","CL20","CL30",
"CL31","CL32,CL33","CL34","CL35","CL69","CL90","ML00","PL03",
"PL20","PL30","PL31","PL33,CA00", "CA01", "CA03", "CA04","CA02",
"PA00", "PA01", "PA02", "PA03", "PA04,PL34","PL35","PL40","PL90"
};
var sum = (
from account in context.Accounts
from owner in account.AccountOwners
where owner.AccountOwnerRegistryId == ownerRegistryId
where !excludeTypes.Contains(account.AccountType)
where account.StateChangeDate == null
||
EntityFunctions.DiffMonths(account.StateChangeDate, DateTime.Now)
<= maxStateChangeMonth
where includOtherPayments.Contains(account.AccountType) ||
!account.AccountType.Contains("Overdra") || !account.AccountType.Contains("Mortgage")
|| !account.AccountType.Contains("Revolv") || !account.AccountType.Contains("*Credit*Card*")
where account.AccountStatusId != excludeStatusId
select (decimal?)account.MinimumInstallment).ToList()
.Sum(minimumInstallment => Math.Abs((decimal)(minimumInstallment)));
return sum;
但是SQL返回0,而LINq返回23456.我知道问题在于LINQ中的paranthesis或where语句的顺序。请建议我解决。
答案 0 :(得分:1)
您可以尝试将LINQ查询放入LINQPad。它是一个有用的免费工具,它将向您显示LINQ查询生成的原始SQL,以帮助您进行调试。它适用于LINQ-to-SQL和实体框架查询。
答案 1 :(得分:0)
从第一眼看主要区别是:
- SQL查询中的FTS函数contains
- LINQ查询中的方法Contains
(转换为like
,而不是转换为FTS调用)
如果要使用FTS,则应使用表值函数(TVF)或存储过程(SP)。还有一些其他选项(例如,ExecuteQuery),但我觉得它们不方便。