LINQ to Entities select all entries in many-to-many relationship

前端 未结 1 337
一整个雨季
一整个雨季 2021-01-16 07:06

I have 3 MySql tables: Students, Classes and StudentsInClasses.

The Entity Framework translates these into two entities

相关标签:
1条回答
  • 2021-01-16 07:39

    How about:

    var query = from @class in db.Classes
                from student in @class.Students
                select new { ClassId = @class.ID, Student = student };
    
    var lookup = query.ToLookup(x => x.ClassId,
                                x => x.Student);
    

    (I suspect a Lookup is more appropriate than a HashSet here.)

    EDIT: If you don't want to use query expressions:

    var query = db.Classes
                  .SelectMany(@class => @class.Students,
                              (@class, student) => new { ClassId = @class.ID,
                                                         Student = student });
    
    0 讨论(0)
提交回复
热议问题