简体   繁体   中英

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

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?

This is the best answer to this question.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM