简体   繁体   English

为什么SqlQuery比在视图上使用LINQ表达式快得多?

[英]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. 我想从一个视图查询数据,这是一个包含583,000条记录的表的视图。 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 这是生成的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. 我运行了5次查询。 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 第一次调用花了我350ms ,下次调用平均花了我150ms这个查询太慢了,所以我把查询更改为这样

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! 我跑了5次第一次通话花了我40ms ,接下来的电话平均只花了我1ms

Do anyone has any ideas what I did wrong? 有没有人有任何想法我做错了什么?

Environment 环境

  • Entity Framework 5.0 实体框架5.0
  • Oracle 11g Database Oracle 11g数据库
  • ODP.NET 11.2 Release 3 ODP.NET 11.2第3版
  • .NET Framework 4.5 .NET Framework 4.5

Isn't it that it takes that 150ms only the first time it ran ?. 是不是它第一次运行需要150ms? Every consecutive call should take around that 1ms you stated. 每次连续呼叫都应该花费你所说的1ms左右。 LinqToSql has to compile the query first to get SQL. LinqToSql必须首先编译查询以获取SQL。 Take a look at LinqToSql Precompiling queries benefit? 看一下LinqToSql预编译查询的好处?

This is the best answer to this question. 这是这个问题的最佳答案。

https://community.oracle.com/message/10481253 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 . 花费的时间大约是150毫秒 But if I tried 但如果我试过

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

The time spent is back to 1ms . 花费的时间回到1 毫秒 I'll ask an another question accordingly. 我会相应地问另一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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