2016-12-01 77 views
0

我試圖用下面顯示的數據得到以下結果。我不知道如何使用linq group來實現結果。任何人都可以請幫助如何解決這個問題?我正在使用EntityFramework來獲取實體。C#linq groupby與多對多表記錄

public class Student 
{ 
    public long StudentId { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<StudentCourse> Courses { get; set; }  
} 

public class Course 
{ 
    public long CourseId { get; set; } 
    public string Name { get; set; } 
    public virtual ICollection<StudentCourse> Students { get; set; } 
} 

public class StudentCourse 
{ 
    public virtual long StudentId { get; set; } 
    public virtual Student Student { get; set; } 

    public virtual long CourseId { get; set; } 
    public virtual Course Course { get; set; } 

    public string Location { get; set; } 
} 

示例數據:

Student 
------- 
StudentId Name 
8   Stud8 

Course: 
------ 
CourseId Name 
88   Course88 
148   Course148 
196   Course196 
453   Course453 

StudentCourse: (StudentId + CourseId + Location makes the uniqueness) 
------------ 
StudentId CourseId Location  
8   88   Location 88 
8   88   Location 89 
8   148   Location 148  
8   196   Location 196  
8   453   Location 453  

Expected Result for StudentId 8: 

CourseId Name  Location 
-------- -----  ------- 
88   Course88 Location 88 
88   Course88 Location 89 
148   Course148 Location 148  
196   Course196 Location 196  
453   Course453 Location 453 

如上述例子所示,課程可以重複不同的位置。

如何使用C#linq group by得到上述結果。我試過以下內容:

var courses = context.courses.Select(g => new 
    { 
     Course = g, 
     Location = g.Students.FirstOrDefault(m => m.StudentId == studentId).Location, 
    }); 

    but i am not getting the right course for the same recipe. 

以下代碼適用於我。但想知道是否有更好的方法來做到這一點。我加入的附加項目

var existingStudentCourses = new List<Model.Entity.StudentCourse>(); 
    var result = new List<CustomClass>(); 
     foreach(var item in context.courses) 
     { 
      var studentCourses = item.Students.Where(x=>x.StudentId == studentId && !existingStudentCourses.Any(y=>y.Equals(x))); 
      var studentCourse = studentCourses.FirstOrDefault(); 
      existingStudentCourses.Add(studentCourse); 
      result.Add(new CustomClass 
      { 
       Course = item, 
       Location = studentCourse.Location 
      }); 
     } 

感謝

回答

0

您可以查詢StudentCourses表?那麼代碼將

var StudentCourses =context.studentCourses.Where(c => c.StudentId == studentId).Select(c => new CustomClass 
    { 
     Course = c.Course , 
     Location = c.Location 
    }) 

如果必須使用過程中的表,你可以嘗試

var StudentCourses = context.courses.Where(c => c.Students.Any(s => s.StudentId == studentId)).Select(c => new CustomClass 
    { 
     Course = c, 
     Location = context.studentCourse.FirstOrDefault(sc=>sc.StudentId==studentId && sc.CourseId==c.CourseId).Location 
    }).Distinct()