Linq to SQL一对多的关系

时间:2012-10-17 11:57:32

标签: c# sql performance linq linq-to-sql

最近几天我一直在努力解决linq querys的表现:

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

2 个答案:

答案 0 :(得分:1)

使用sql-debug-visualizer检出生成的sql,然后复制生成的SQL并从SQL Client运行它,看看需要多长时间。如果需要接近1分钟,则需要通过添加索引和/或存储过程或创建视图等来提高数据库级别的性能。

如果上面没有花费太多时间,你可以随时创建Stored Procedure and call that using LINQ to SQ L。

还有一个建议是使用实体框架if you can change to because这是未来。

答案 1 :(得分: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列和Answer - UidQuestion列。 / p>

另见这里。您可能希望使用.AsQueryable()代替ToList()来延迟执行

Do you ToList()?