Q:

Analyzing queries by Entity Framework

I'm learning Entity Framework and I need some explanation. 
Let's assume I've created some many-to-many relationship, so that we have table Students and Courses, and entity of each type can have many entities of the other types. 
Next, I have a gridview where I want to display table with two columns describing student's name and all the courses he's assigned to. For this purpose in the Page_Load event of my WebForm I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
    MyModel dbContext = new MyModel();
    GridView1.DataSource = from student in dbContext.Students
                                .Include("Courses").ToList()
                           select new
                                   {
                                       Name = student.StudentName,
                                       Courses = string.Join(",", student.Courses.Select(c => c.CourseName))
                                   };
    GridView1.DataBind();
}

Now it works, but notice, that the query isn't really analyzed by Entity Framework, because the line:
GridView1.DataSource = from student in dbContext.Students.Include("Courses").ToList()

makes that this query is analyzed by LINQ to Objects provider. If I don't use ToList() method but instead I would like to write:
var query = from student in dbContext.Students.Include("Courses")
            select new { ... };
GridView1.DataSource = query.ToList();
GridView1.DataBind();

then I've got the exception that the Join() method is not recognized by Entity Framework. I could live with that, but guess the application would work faster if the query was analyzed by EF's engine, am I right?
If so, how I could rewrite the code assigning string to Courses property of my anonymous type to get the same result?

A:

The only real problem with the way you've done it so far is that, if you want to apply filtering, it would be applied after the call to ToList, so would be done in memory.
I would split your query into 2 parts. The first part would read the data from the database (and would allow you to include where clauses) while the second would map the objects into the format.
protected void Page_Load(object sender, EventArgs e)
{
    using (var dbContext = new MyModel())
    {
        var students = (from student in dbContext.Students
                        /*optional where clause*/
                        select new
                               {
                                   Name = student.StudentName,
                                   Courses = student.Courses.Select(c => c.CourseName)
                               }).ToList();
        GridView1.DataSource = students.Select(s => new { s.Name, Courses = String.Join(",", s.Courses)}).ToList();
        GridView1.DataBind();
    }
}

It's worth mentioning that you could possibly recreate this entirely in EF using Aggregate, but I don't really think it's necessary.

