带外键的实体框架运行非常慢

时间:2019-06-04 14:25:23

标签: c# linq entity-framework-4 sqlperformance

在Entity Framework代码中都可以使用该代码,该代码使用数据库中的外键创建带有子对象的对象。 生成的SQL查询是立即的,但是EF代码将永远运行...

1。检查EF的FK是否与DB的FK匹配 2.检查EF和DB的数据类型是否匹配 3.检查FK是否具有索引

EF代码

DAL.NachshonDBDataContext oDB = Config.GetDB(); 
var oQuery =
          from oDALMentor in oDB.Mentors 
          orderby oDALMentor.User.sDisplayName
          select new
          {
              oDALMentor,
              oDALUser = oDALMentor.User,
              oDALSector = oDALMentor.LU_Sector,
              oDALAcademicInstitute = oDALMentor.LU_AcademicInstitute,
              oDALMentoringFramework = oDALMentor.LU_MentoringFramework,
              oDALMentoringCoordinator = oDALMentor.LU_MentoringCoordinator,
              oDALMentorQuestionnaires = oDALMentor.MentorQuestionnaires,
              oDALMentorLangs = oDALMentor.MentorLangs,
};
var result = oQuery.AsParallel().ToList(); // takes very long time

生成的SQL

SELECT * -- asterisk instead of all the generated fields
    (
    SELECT COUNT(*)
    FROM dbo.MentorQuestionnaires AS t7
    WHERE t7.gUserID = t0.gUserID
    ) AS value
FROM dbo.Mentors AS t0
INNER JOIN dbo.Users AS t1 ON t1.gUserID = t0.gUserID
INNER JOIN dbo.LU_Sectors AS t2 ON t2.nSectorID = t0.nSectorID
INNER JOIN dbo.LU_AcademicInstitutes AS t3 ON t3.nAcademicInstitueID = 
t0.nAcademicInstituteID
INNER JOIN dbo.LU_MentoringFrameworks AS t4 ON t4.nMentoringFrameworkID = 
t0.nMentoringFrameworkID
INNER JOIN dbo.LU_MentoringCoordinators AS t5 ON t5.nMentorCoordinatorID 
= t0.nMentorCoordinatorID
LEFT OUTER JOIN dbo.MentorQuestionnaires AS t6 ON t6.gUserID = t0.gUserID
WHERE t1.nStatus = 1

查询运行非常快,并检索到1521行

0 个答案:

没有答案