Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I avoid Entity framework use SQL_VARIANT to query?

I use entity framework 6 code first and I have a simple model:

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

And I get a model:

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

or

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

It's sure be fast but not......

I look the SQL in IntelliTrace that generated by EF ORM, like this:

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

I add SET STATISTICS and test it in SSMS.

Table 'Task'. Scan count 1, ...

It use SQL_VARIANT! Execution plan is scan table instead of clustered seeking!

Why EF do it?! Can I avoid it?

(LocalDB with SQL Server 2012)

like image 291
litfal Avatar asked Feb 14 '26 04:02

litfal


1 Answers

I found a problem!

It's cause I look the sql in IntelliTrace.

IntelliTrace will hide all variant and show them as SQL_VARIANT.

I got actual SQL by SQL Server Profiler, the sql is:

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

It's OK that use seeking to query data.

like image 184
litfal Avatar answered Feb 15 '26 19:02

litfal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!