Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In LINQ query, how to order by included table column using .Include()?

I have this table structure: Two tables and a lookup table

I have this LINQ query:

var query = (from p in context.People.Include("PeopleClub").Include("PeopleClub.Club")
             orderby p.Name
             select p).ToList();

Is it possible to do something like this:

var query = (from p in context.People
                              .Include("PeopleClub")
                              .Include("PeopleClub.Club")
             orderby p.Name, p.PeopleClub.DisplaySequence
             select p).ToList();

Update: Using Entity Framework 4.0

Update 2: I give up. See this similar question for another approach. I ended up rewriting my query without the .Include().

like image 346
scw Avatar asked Mar 27 '13 21:03

scw


People also ask

What does include () do in LINQ?

Introduction to LINQ Include. LINQ include helps out to include the related entities which loaded from the database. It allows retrieving the similar entities to be read from database in a same query. LINQ Include() which point towards similar entities must read from the database to get in a single query.

How would you sort the list in ascending order LINQ?

In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order. We don't need to add any ascending condition in the query statement.


1 Answers

Try by navigation properties:

using System.Data.Entity;                                  // notice using

var q = from p in context.People
                          .Include(p => p.PeopleClub)      // notice lambda instead of string
                          .Include(p => p.PeopleClub.Club) // you may not need that though
        orderby p.FirstName, p.ClubPerson.DisplaySequence
        select p;

or regular join:

var q = from p in db.People
        join pc in db.PeopleClub on p.PersonID equals pc.PersonID
        join c in db.Clubs on pc.ClubID equals c.ClubID
        orderby p.FirstName, pc.DisplaySequence
        select p;
like image 164
abatishchev Avatar answered Oct 05 '22 23:10

abatishchev