Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
889 views
in Technique[技术] by (71.8m points)

entity framework - C# linq include before-after where

In linq is there a difference between:

EFDbContext _db = new EFDbContext();



  1)_db.UserQuizes
        .Where(uq => uq.UserId == currentUserId && uq.QuizId == quizId)
        .Include(qz => qz.Quiz.VerbalQuizes.Select(q => q.Question)).First()

2)_db.UserQuizes
        .Include(qz => qz.Quiz.VerbalQuizes.Select(q => q.Question))                          
        .Where(uq => uq.UserId == currentUserId && uq.QuizId == quizId).First()

   3)_db.UserQuizes
            .Include(qz => qz.Quiz.VerbalQuizes.Select(q => q.Question))
             First(uq => uq.UserId == currentUserId && uq.QuizId == quizId)

Notice that first query uses include after where and second before where, but result is the same. Also how to see actual sql query? In this particular case perfomance is my main goal, can i improve the query? i need to change two properties : UserQuizes property, and UserQuizes-> VerbalQuizes-> Question property.

Would it be better to split up it two queries or use it like as it is

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Ordering of instructions like you've shown often won't make a difference in EF or LINQ to SQL. The query builder turns your entire LINQ statement into an abstract logical representation, and then another pass converts the logical structure into a SQL statement. So the WHERE predicates are all going to end up in the same place. The predicates inside a First() just get pushed over to the WHERE clause. The Include statements also get accumulated and projected to JOINs to include the extra columns needed to produce the included entity.

So the short answer is that EF will usually produce the most logical SQL statement regardless of the order in which you constructed your LINQ statement. If you need to tune it further, you should look at a stored procedure where you can hand-craft the SQL.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...