1

I have two tables, for example, Student and Grade.
Those two tables have a relationship with many-to-many, so the table is StudentGrade.
By using the .SelectMany query, I can retrieve all records which have a relation.
For example,

var myResult = myDb.Student.SelectMany(x => x.Grade).ToList();

But let say I add a new record just to the Student table, which has no relation with Grade, this new record cannot be retrieved by using the query above.
How can I retrieve all data including this new one?

Student
Id     Name    Age
1      AAA     4
2      BBB     5
3      CCC     6
4      DDD     7

Grade
Id    Name
1     G1
2     G2
3     G3
4     G4

StudentGrade
Student    Grade
2          1
2          2
2          3
3          3

Require result:
Id     Name    Age   Grade
1      AAA     4  
2      BBB     5     G1
2      BBB     5     G2
2      BBB     5     G3
3      CCC     6     G3    
4      DDD     7 

I found full outer join would help but will it work in a many-to-many relationship?
How can I overcome this issue ?

Steven Sann
  • 478
  • 1
  • 7
  • 27

2 Answers2

0
  var result = (from s in myDb.Student 
    from g in myDb.Grades 
    where !g.Select(x => x.Student).Contains(s) || g.Student == null || g.Student == s).ToList();

As long as I understand your question this should give you

  • all Students that have grades,
  • all Grades with no students,
  • and all Students with no grades. I have not seen your models but this should help
Vladimir
  • 322
  • 1
  • 17
0

var myResult = myDb.Student.SelectMany(x => x.Grade).ToList();

This query "means" retrieve all the Grades that have a Student. If you want the Students, select Student and Include the Grades if you want.

var myResult = myDb.Students.Include(x => x.Grades).ToList();
David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67