2014-09-05 66 views
3

我6碼第一次使用實體框架和我有一個簡單的模型:我可以避免實體框架使用SQL_VARIANT進行查詢嗎?

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做到這一點?我可以避免它嗎?

(LocalDB with SQL Server 2012)

+0

什麼是任務表定義(至少[aid]列定義)? – 2014-09-05 15:14:27

+0

[aid]是int集羣主鍵。 – litfal 2014-09-05 16:06:41

回答

4

我發現了一個問題!

這是因爲我看在IntelliTrace sql。

的IntelliTrace將隱藏所有變種,並告訴他們爲SQL_VARIANT

我由SQL Server探查了實際的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 

它的確定是使用求查詢數據。

相關問題