Why is Entity Framework taking 30 seconds to load records when the generated query only takes 1/2 of a second?

前端 未结 4 1152
深忆病人
深忆病人 2020-12-08 16:34

The executeTime below is 30 seconds the first time, and 25 seconds the next time I execute the same set of code. When watching in SQL Profiler, I immediately see a login, t

4条回答
  •  执笔经年
    2020-12-08 17:12

    I had this exact same problem, my query was taking 40 seconds.

    I found the problem was with the .Include("table_name") functions. The more of these I had, the worse it was. Instead I changed my code to Lazy Load all the data I needed right after the query, this knocked the total time down to about 1.5 seconds from 40 seconds. As far as I know, this accomplishes the exact same thing.

    So for your code it would be something like this:

    var groupQuery = (from g in context.Groups
                where g.GroupKey == 6 
                select g).OfType(); 
    
    var groups = groupQuery.ToList();
    
    foreach (var g in groups)
    {
        // Assuming Dealcontract is an Object, not a Collection of Objects
        g.DealContractReference.Load();
        if (g.DealContract != null)
        {
            foreach (var d in g.DealContract)
            {
                // If the Reference is to a collection, you can just to a Straight ".Load"
                //  if it is an object, you call ".Load" on the refence instead like with "g.DealContractReference" above
                d.Contracts.Load();
                foreach (var c in d.Contracts)
                {
                    c.AdvertiserAccountType1Reference.Load();
                    // etc....
                }
            }
        }
    }
    

    Incidentally, if you were to add this line of code above the query in your current code, it would knock the time down to about 4-5 seconds (still too ling in my option) From what I understand, the MergeOption.NoTracking option disables a lot of the tracking overhead for updating and inserting stuff back into the database:

    context.groups.MergeOption = MergeOption.NoTracking;
    

提交回复
热议问题