简体   繁体   中英

EF Linq query is 100x slower than stored procedure

I ran a test execute a Linq query compared to a stored procedure call using both in EF DataContext . And it seems like the stored procedure call is around 100x faster - why is that?

LINQ example:

 var results = (from I in db.MyTable
                select I).toList();

Stored procedure:

  ....
  SELECT * 
  FROM myTable T
    INNER JOIN TABLE2
    INNER JOIN TABLE3

CALL to stored procedure

var results = this.Database.SQlQuery<MyModel>("spMyStorePro").ToList()      

The Linq execution would take like 10-15 seconds, while the stored procedure call would take like 1-2 sec if not less.

the model contains several entities

 MyTableModel
      public int KEY {Get;set;}

      public virtual TABLE1 table1Info {get; set;}
      public virtual TABLE2 table2Info {get; set;}

Is this common or am I setting up my model incorrectly?

One thing I would mention is that my MODEL has a few nested models that may cause the slow performance.

UPDATED

So here is something interesting I found:

I grab the sql query from sql monitor that LINQ spits out.

it looks something like this

SELECT [EXtent1].COL1, [Extent2].COL2 FROM table1 as extent1 left outer join table 2 as extent2

if I execute the above query it takes 9 sec to execute each time. The interesting is that if I remove COL2 from the select list, it executes in 2 secs.

WHy would removing a column from the select list improve the speed? This is outside of EF and LINQ now, this is a question in sql

Things to review

  • Is there any sort of WHERE clause in your stored procedure that is not in your EF query
  • Is the stored procedure returning a nested hierarchy
  • When you say that your "model has several nested models", have you tried configuring the relationships code-first, and excluding unnecessary children/descendants? See below...

var query = context.Query<Thing>(
       include: t => t.Child.Select(v => v.Grandchild))
       .Where(t => t.Foo == "bar"); // includes descendants

var query = context.Query<Thing>()
       .Where(t => t.Foo == "bar"); // excludes descendants

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