2012-10-17 157 views
3

過去幾天我用LINQ querys表現掙扎:LINQ to SQL的一對多關係

LinqConnectionDataContext context = new LinqConnectionDataContext(); 
System.Data.Linq.DataLoadOptions options = new System.Data.Linq.DataLoadOptions(); 
options.LoadWith<Question>(x => x.Answers); 
options.LoadWith<Question>(x => x.QuestionVotes); 
options.LoadWith<Answer>(x => x.AnswerVotes); 
context.LoadOptions = options; 
var query =(from c in context.Questions 
      where c.UidUser == userGuid 
      && c.Answers.Any() == true 
      select new 
      { 
       c.Uid, 
       c.Content, 
       c.UidUser, 
       QuestionVote = from qv in c.QuestionVotes where qv.UidQuestion == c.Uid && qv.UidUser == userGuid select new {qv.UidQuestion, qv.UidUser }, 
       Answer = from d in c.Answers 
         where d.UidQuestion == c.Uid 
         select new 
         { 
          d.Uid, 
          d.UidUser, 
          d.Conetent, 
          AnswerVote = from av in d.AnswerVotes where av.UidAnswer == d.Uid && av.UidUser == userGuid select new { av.UidAnswer, av.UidUser } 
         } 
      }).ToList(); 

查詢必須通過5000行中運行,它需要長達1分鐘。我如何提高此查詢的性能?

更新:

enter image description here

+0

存儲過程?你用於JOIN的列和SQL端的WHERE子句的索引? – tranceporter

+0

更新我的問題與表格圖片 – Timsen

+0

檢查我的答案 – tranceporter

回答

1

讓你開始的東西。

CREATE PROCEDURE GetQuestionsAndAnswers 
(
    @UserGuid VARCHAR(100) 
) 
AS 
BEGIN 

SELECT 
c.Uid, 
c.Content, 
c.UidUser, 
qv.UidQuestion, 
qv.UidUser, 
av.UidAnswer, 
av.UidUser, 
av.Content, 
d.Uid, 
d.UidUser, 
d.Content 
FROM Question c 
INNER JOIN QuestionVotes qv ON qv.UidQuestion = c.Uid AND qv.UidUser = @UserGuid 
INNER JOIN Answers d ON d.UidQuestion = c.Uid 
INNER JOIN AnswerVotes av ON av.UidAnswer = d.Uid AND av.UidUser = @UserGuid 
WHERE c.UidUser = @UserGuid 

END 

您將已經聚集在默認情況下主列的索引(剛剛證實這一點在你的數據庫端),以及你希望非聚集索引上QuestionVote - UidUser柱,AnswerVote - UidUser列,答案 - UidQuestion列。

也看看這裏。你可能想使用.AsQueryable()而不是ToList()延期執行

Do you ToList()?

+0

哦..快照...問題與這存儲precidure是它創建內部連接,但我有什麼是:問題和QuestionVotes有一對多的realtionship,與答案和AnswerVote – Timsen

+0

相同,那麼你可以使用question.uid group. clause,answer.uid – tranceporter

1

經過了使用sql-debug-visualizer,然後複製生成的SQL和SQL客戶端運行它,看看它是如何花費的時間生成的SQL。如果需要近1分鐘,你需要通過添加索引和/或存儲過程或創建視圖等

到imporve在數據庫級性能若以上沒有采取太多的時間,你可以隨時創建Stored Procedure and call that using LINQ to SQ L.

還有一個建議是使用實體框架if you can change to because這是未來。

+0

它幾乎沒有時間... – Timsen

+0

如何.ToToList是需要時間... – Timsen

+0

看到更新的答案... –