开发者

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 propert开发者_如何学编程ies?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜