所以我正在对访问我的 SQLServer 数据库的不同方法进行一些分析。我做了 vanilla TSQL、CompiledQuery 和非编译的 Linq 语句。
正如预期的那样,性能以相同的顺序进行,但在分析后两者时我注意到了一些奇怪的东西。
CompiledQuery 生成的 SQL 比普通的旧语句生成的要好得多。
本地 SQLExpress 数据库;表称为'foreignTable',ColumnA是int,主键(索引);ColumnB 是一个随机整数。
Func<testingDatabaseEntities1, int, int> GetByPK = CompiledQuery.Compile((testingDatabaseEntities1 ft, int key)
=> (ft.foreignTable.Where(x => x.ColumnA == key).FirstOrDefault().ColumnB));
生成
SELECT
[Project1].[ColumnB] AS [ColumnB]
FROM ( SELECT cast(1 as bit) AS X ) AS [SingleRowTable1]
LEFT OUTER JOIN (SELECT TOP (1)
[Extent1].[ColumnB] AS [ColumnB]
FROM [dbo].[foreignTable] AS [Extent1]
WHERE [Extent1].[ColumnA] = @p__linq__1 ) AS [Project1] ON 1 = 1
对于生成的代码,这真的不算太糟糕。
但是当我做简单的 Linq 语句时:
entity.foreignTable.Where(x => x.ColumnA == searchForMe).FirstOrDefault().ColumnB
它生成:
SELECT
[Limit1].[C1] AS [C1],
[Limit1].[ColumnA] AS [ColumnA],
[Limit1].[ColumnB] AS [ColumnB],
[Limit1].[FKColumn] AS [FKColumn]
FROM ( SELECT TOP (1)
[Extent1].[ColumnA] AS [ColumnA],
[Extent1].[ColumnB] AS [ColumnB],
[Extent2].[FKColumn] AS [FKColumn],
1 AS [C1]
FROM [dbo].[foreignTable] AS [Extent1]
LEFT OUTER JOIN (SELECT
[Table_2].[FKColumn] AS [FKColumn],
[Table_2].[SomeText] AS [SomeText]
FROM [dbo].[Table_2] AS [Table_2]) AS [Extent2] ON [Extent1].[ColumnA] = [Extent2].[FKColumn]
WHERE [Extent1].[ColumnA] = @p__linq__7
) AS [Limit1]
这太糟糕了。
所以我想问题是:是否可以为实体提供与 CompiledQuery 相同数量的 SQL 吸力的常规 Linq?