想知道数据库方面的区别,编写了2个Entity Framework查询。
让
from u in Users
let noVowel = u.FirstName.Replace("a","").Replace("e","").Replace("i","")
where noVowel.Length >5
select new {u.FirstName, noVowel}
进入
from u in Users
select u.FirstName.Replace("a","").Replace("e","").Replace("i","")
into noVowel
where noVowel.Length >5
select noVowel
生成的SQL几乎相同。SQL并不完美,在2个地方(where和select)重复相同的字符串处理代码。
SELECT 1 AS [C1], [Extent1].[FirstName] AS [FirstName],
REPLACE(REPLACE(REPLACE([Extent1].[FirstName], N'a', N''), N'e', N''), N'i', N'') AS [C2]
FROM [dbo].[User] AS [Extent1]
WHERE ( CAST(LEN(REPLACE(REPLACE(REPLACE([Extent1].[FirstName], N'a', N''), N'e', N''), N'i', N'')) AS int)) > 5
GO
SELECT
REPLACE(REPLACE(REPLACE([Extent1].[FirstName], N'a', N''), N'e', N''), N'i', N'') AS [C1]
FROM [dbo].[User] AS [Extent1]
WHERE ( CAST(LEN(REPLACE(REPLACE(REPLACE([Extent1].[FirstName], N'a', N''), N'e', N''), N'i', N'')) AS int)) > 5
这是LINQ-to-SQL生成的SQL
-- Region Parameters
DECLARE @p0 NVarChar(1000) = 'a'
DECLARE @p1 NVarChar(1000) = ''
DECLARE @p2 NVarChar(1000) = 'e'
DECLARE @p3 NVarChar(1000) = ''
DECLARE @p4 NVarChar(1000) = 'i'
DECLARE @p5 NVarChar(1000) = ''
DECLARE @p6 Int = 5
-- EndRegion
SELECT [t1].[FirstName], [t1].[value] AS [noVowel]
FROM (
SELECT [t0].[FirstName], REPLACE(REPLACE(REPLACE([t0].[FirstName], @p0, @p1), @p2, @p3), @p4, @p5) AS [value]
FROM [User] AS [t0]
) AS [t1]
WHERE LEN([t1].[value]) > @p6
GO
-- Region Parameters
DECLARE @p0 NVarChar(1000) = 'a'
DECLARE @p1 NVarChar(1000) = ''
DECLARE @p2 NVarChar(1000) = 'e'
DECLARE @p3 NVarChar(1000) = ''
DECLARE @p4 NVarChar(1000) = 'i'
DECLARE @p5 NVarChar(1000) = ''
DECLARE @p6 Int = 5
-- EndRegion
SELECT [t1].[value]
FROM (
SELECT REPLACE(REPLACE(REPLACE([t0].[FirstName], @p0, @p1), @p2, @p3), @p4, @p5) AS [value]
FROM [User] AS [t0]
) AS [t1]
WHERE LEN([t1].[value]) > @p6
似乎Linq-to-SQL比Entity Framework聪明,字符串处理仅执行一次。
let
示例中是否有错字-where noVowel
,那是什么noVowel
情况?