Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • Entity Framework 5.0
  • Oracle 11g Database
  • ODP.NET 11.2 Release 3
  • .NET Framework 4.5
like image 388
Moozz Avatar asked Jan 09 '15 07:01

Moozz


2 Answers

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?

like image 50
smiech Avatar answered Oct 15 '22 16:10

smiech


This is the best answer to this question.

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

like image 33
Moozz Avatar answered Oct 15 '22 17:10

Moozz