简体   繁体   中英

slow entity framework query , but fast Generated SQL

please consider this model 在此处输入图片说明

it's for a fitness center management app

ADHERANT is the members table

INSCRIPTION is the subscription table

SEANCE is the individual sessions table

the seance table contain very fews rows (around 7000)

now the query :

  var q = from n in ctx.SEANCES
                select new SeanceJournalType()
                        {
                            ID_ADHERANT = n.INSCRIPTION.INS_ID_ADHERANT,
                            ADH_NOM = n.INSCRIPTION.ADHERANT.ADH_NOM,
                            ADH_PRENOM = n.INSCRIPTION.ADHERANT.ADH_PRENOM,
                            ADH_PHOTO = n.INSCRIPTION.ADHERANT.ADH_PHOTO,
                            SEA_DEBUT = n.SEA_DEBUT
                        };

                var h = q.ToList();

this take around 3 seconds wich is an eternity, the same generated SQL query is almost instantaneous

SELECT 
1 AS "C1", 
"C"."INS_ID_ADHERANT" AS "INS_ID_ADHERANT", 
"E"."ADH_NOM" AS "ADH_NOM", 
"E"."ADH_PRENOM" AS "ADH_PRENOM", 
"E"."ADH_PHOTO" AS "ADH_PHOTO", 
"B"."SEA_DEBUT" AS "SEA_DEBUT"
FROM   "TMP_SEANCES" AS "B"
LEFT OUTER JOIN "INSCRIPTIONS" AS "C" ON "B"."INS_ID_INSCRIPTION" = "C"."ID_INSCRIPTION"
LEFT OUTER JOIN "ADHERANTS" AS "E" ON "C"."INS_ID_ADHERANT" = "E"."ID_ADHERANT"

any idea on what's going on please, or how to fix that ?

thanks

it needs some research to optimize this :

if you neglect the data transfer from the db to the server then as Ivan Stoev Suggested calling the ToList method is the expensive part

as for improving the performance it depends on your needs:

1.if you need add-delete functionality at the server side it is probably best to stick with the list

2.if no need for add-delete then consider ICollection ,, or even better

3.if you have more conditions which will customize the query even more best use IQuerable

customizing the query like selecting a single record based on a condition :

var q = from n in ctx.SEA.... // your query without ToList()
q.where(x=>"some condition") //let`s say x.Id=1

only one record will be transferred from the database to the server

but with the ToList Conversion all the records will be transferred to the server then the condition will be calculated

although it is not always the best to use IQuerable it depends on your business need

for more references check this and this

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