Dismissile
Dismissile

Reputation: 33071

Proper Way to Write Entity Framework Queries

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?

Upvotes: 1

Views: 717

Answers (1)

Jan
Jan

Reputation: 8141

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.

Upvotes: 4

Related Questions