Entity Framework query performance differs extrem with raw SQL execution

后端 未结 4 1694
生来不讨喜
生来不讨喜 2021-01-31 04:51

I have a question about Entity Framework query execution performance.

Schema:

I have a table structure like this:

CREATE TABLE [         


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-31 05:23

    When EF runs the query, it wraps it and runs it with sp_executesql, which means the execution plan will be cached in the stored procedure execution plan cache. Due to differences (parameter sniffing etc) in how the raw sql statement vs the SP version have their execution plans built, the two can differ.

    When running the EF (sp wrapped) version, SQL server is most likely using a more generic execution plan that covers a wider range of timestamps than the values you are actually passing in.

    That said, to reduce the chance of SQL server trying something "funny" with hash joins etc, the first things I would do are:

    1) Index the columns used in the where clause, and in joins

    create index ix_DataLogger_ProjectID on DataLogger (ProjectID);
    create index ix_DCDistributionBox_DataLoggerID on DCDistributionBox (DataLoggerID);
    create index ix_DCString_DCDistributionBoxID on DCString (DCDistributionBoxID);
    

    2) Do explicit joins in the Linq query to eliminate the or ProductID is null part

提交回复
热议问题