Moozz
Moozz

Reputation: 609

Why is SqlQuery a lot faster than using LINQ expression on views?

I want to query data from a view, which is a view of a table contains 583,000 records. So I write a simple query to query from the view like this

var uuid = "AB1-23456";
dbSet.SingleOrDefault(x => x.UserKey == uuid);

This is the generated sql

SELECT "Extent1"."UserKey" AS "UserKey", 
       CAST("Extent1"."IsDeleted" AS number(3,0)) AS "C1", 
       "Extent1"."FirstName" AS "FirstName", 
       "Extent1"."LastName" AS "LastName", 
       "Extent1"."UserLogin" AS "UserLogin", 
       "Extent1"."AccLocationKey" AS "AccLocationKey", 
       "Extent1"."CompanyKey" AS "CompanyKey"
FROM "UsersView" "Extent1"
WHERE ('AB1-23456' = "Extent1"."UserKey")

I ran the query for 5 times. The first call took me 350ms and next calls took me 150ms on average on this query which was too slow, so I changed the query to be like this

var queryString = 
    "SELECT \"Extent1\".\"UserKey\" AS \"UserKey\", " +
            "CAST( \"Extent1\".\"IsDeleted\" AS number(3,0)) AS \"IsDeleted\", " +
            "\"Extent1\".\"FirstName\" AS \"FirstName\", " +
            "\"Extent1\".\"LastName\" AS \"LastName\", " +
            "\"Extent1\".\"UserLogin\" AS \"UserLogin\", " +
            "\"Extent1\".\"AccLocationKey\" AS \"AccLocationKey\", " +
            "\"Extent1\".\"CompanyKey\" AS \"CompanyKey\" " +
    "FROM \"UsersView\" \"Extent1\" " +
    "WHERE ('AB1-23456' = \"Extent1\".\"UserKey\")";
dbSet.SqlQuery(queryString).SingleOrDefault();

I ran it for 5 times The first call took me 40ms and next calls took me only 1ms on average!

Do anyone has any ideas what I did wrong?

Environment

Upvotes: 9

Views: 944

Answers (3)

Moozz
Moozz

Reputation: 609

This is the best answer to this question.

https://community.oracle.com/message/10481253

Upvotes: 1

Moozz
Moozz

Reputation: 609

This problem is not valid anymore.

var uuid = "AB1-23456";
dbSet.SingleOrDefault(x => x.UserKey == uuid);

The time spent is around 150ms. But if I tried

dbSet.SingleOrDefault(x => x.UserKey == "AB1-23456");

The time spent is back to 1ms. I'll ask an another question accordingly.

Upvotes: 0

smiech
smiech

Reputation: 750

Isn't it that it takes that 150ms only the first time it ran?. Every consecutive call should take around that 1ms you stated. LinqToSql has to compile the query first to get SQL. Take a look at LinqToSql Precompiling queries benefit?

Upvotes: 4

Related Questions