1

I want to know the proper way to write a query like this:

var questions = from q in db.Questions
                join sq in db.SurveyQuestions on q.QuestionID = sq.QuestionID
                where sq.SurveyID == 1
                orderby sq.Order
                select q;

I basically want to select everything from the Questions table where it matches a value in a different table.

I think it's also possible to write the query like so:

var questions = from q in db.Questions
                from sq in q.SurveyQuestions
                where sq.SurveyID == 1
                orderby sq.Order
                select q;

This query does not work but is more along the lines of how I am thinking:

var questions = from q in db.Questions
                where q.SurveyQuestions.SurveyID == 1
                orderby q.SurveyQuestions.Order
                select q;

What is the right way to write these types of queries in entity framework using the navigation properties?

1 Answer 1

4

Haven't tested this but I assume this is what you're looking for

var questions = from sq in db.SurveyQuestions
                where sq.SurveyID == 1
                orderby sq.Order
                select sq.Question;

Where Question is a navigation property on SurveyQuestion.

You are working with entities and not with database tables. This type of queries is exactly what EF is about. You don't have to think in terms of database tables like you do in your first query. Instead you can start immediately filtering on SurveyQuestions, which is more intuitive. The navigation properties will abstract away the joins you would have used if you would have operated directly on the database.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes that is probably more along the lines of what I'm looking for. I will try this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.