我可以避免Entity框架使用SQL_VARIANT来查询吗?

时间:2014-09-05 14:44:38

标签: c# sql entity-framework

我首先使用实体​​框架6代码,我有一个简单的模型:

public class Task
{
    [Key]
    public int aid {get;set;}
    [MaxLength(256)]
    public string Memo {get;set;}
}

我得到了一个模特:

int id = 3;
from t in db.Tasks
where t.aid == id
select t;

int id = 3;
db.Tasks.Find(id);

肯定会很快但不是......

我查看由EF ORM生成的IntelliTrace中的SQL,如下所示:

DECLARE @p__linq__0 AS SQL_VARIANT;
SET @p__linq__0 = 3;

SET STATISTICS TIME ON 
SET STATISTICS IO ON 

SELECT 
    [Limit1].[aid] AS [aid], 
    [Limit1].[Memo] AS [Memo]
    FROM ( SELECT TOP (1) 
        [Extent1].[aid] AS [aid], 
        [Extent1].[Memo] AS [Memo]
        FROM [dbo].[Task] AS [Extent1]
        WHERE [Extent1].[aid] = @p__linq__0
    )  AS [Limit1]

SET STATISTICS TIME OFF
SET STATISTICS IO OFF

我添加SET STATISTICS并在SSMS中测试它。

表'任务'。 扫描计数1 ,...

使用 SQL_VARIANT !执行计划是扫描表而不是集群搜索!

为什么EF会这样做?!我可以避免吗?

(使用SQL Server 2012的LocalDB)

1 个答案:

答案 0 :(得分:4)

我发现了一个问题!

它的原因我在IntelliTrace中查看sql

IntelliTrace将隐藏所有变体并将其显示为为SQL_VARIANT

我通过SQL Server Profiler获得了实际的SQL,sql是:

exec sp_executesql N'SELECT 
[Limit1].[aid] AS [aid], 
[Limit1].[Memo] AS [Memo]
FROM ( SELECT TOP (1) 
    [Extent1].[aid] AS [aid], 
    [Extent1].[Memo] AS [Memo]
    FROM [dbo].[Task] AS [Extent1]
    WHERE [Extent1].[aid] = @p__linq__0
)  AS [Limit1]',N'@p__linq__0 int',@p__linq__0=3

可以使用寻求查询数据。