在下面的示例中,我在INT字段上查询实体。以下是我的情况的示例:
int test =1;
var listExample= _db.EntityTable.Where(x => x.StatusId == test).ToList();
当我查看生成的SQL时,它使用SQL_VARIANT作为变量声明,因此未正确使用表上的索引,从而导致整个表扫描。
下面是生成的SQL的示例:
DECLARE @p__linq__0 AS SQL_VARIANT;
SET @p__linq__0 = NULL;
SELECT
[Extent1].[id] AS [id],
FROM [dbo].[tbl_table_example] AS [Extent1]
WHERE [Extent1].[status_id] = @p__linq__0
反正有没有办法让EF尝试将变量定义为所查询的属性类型?
答案 0 :(得分:0)
我认为这只是Visual Studio IntelliTrace生成与实际执行的SqlCommand相对应的SQL批处理方式的错误或限制。我转载了此内容,但查看了通过SQL事件探查器发送的SQL,它看起来是正确的:
exec sp_executesql N'SELECT [x].[Id], [x].[StatusId]
FROM [EntityTable] AS [x]
WHERE [x].[StatusId] = @__test_0',N'@__test_0 int',@__test_0=1
此外EF日志记录报告正确的参数类型:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[StatusId] AS [StatusId]
FROM [dbo].[EntityTables] AS [Extent1]
WHERE [Extent1].[StatusId] = @p__linq__0
-- p__linq__0: '1' (Type = Int32, IsNullable = false)
-- Executing at 8/1/2018 9:41:32 AM -05:00
-- Completed in 20 ms with result: SqlDataReader
IntlliTrace输出(请注意第一行的警告)是:
--Type and value data was not available for the following variables. Their values have been set to defaults.
DECLARE @p__linq__0 AS SQL_VARIANT;
SET @p__linq__0 = NULL;
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[StatusId] AS [StatusId]
FROM [dbo].[EntityTables] AS [Extent1]
WHERE [Extent1].[StatusId] = @p__linq__0