在Parent Child关系中返回逗号分隔的字符串

时间:2015-12-29 11:39:10

标签: entity-framework linq

我有一个看起来像这样的数据库结构。

Course
     CourseID-------------
     Name                 |     
                          |    
MultiCourse               |     
      MultiCourseID---------------------------
      MultiCourseName     |                   |
                          |                   | 
MultiCourseDetail         |                   |
      MultiCourseDetailID |                   |
      MultiCourseID       |                   |
      CourseID-------------                   |    
                                              |     
StudentRegistration                           |    
      StudentRegistrationID                   |    
      StudentName                             |    
                                              |    
StudentRegistrationCourse                     |    
      StudentRegistrationCourseID             |    
      StudentRegistrationID                   |     
      MultiCourseID---------------------------

我想列出学生在注册时所用的所有课程(用逗号分隔)。我尝试了以下方式,但它给了我课程列表而不是用逗号分隔的课程

 List<RegistraionVM.RegDataTable> _dTableReg = new List<RegistraionVM.RegDataTable> ();
 _dTableReg = _db.StudentRegistrations
              .AsEnumerable()
              .OrderByDescending(r => r.Id)
              .Select(r => new 
               {                    
                   SoftwareUsed = r.StudentRegistrationCourses
                                 .Select(c => c.MultiCourse.MultiCourseDetails
                                 .Select(mc => mc.Course.Name).Aggregate((m, n) => m + "," + n)).ToList()
                }

1 个答案:

答案 0 :(得分:1)

问题是您过早地调用Aggregate,如果您将第一个Select更改为SelectMany,那么您应该能够将聚合移动到{{1}之后并获得您正在寻找的结果。事实上,一旦做出这种改变,甚至不再需要ToList。这是它的样子:

ToList

如下面的评论中所述,List<RegistraionVM.RegDataTable> _dTableReg = new List<RegistraionVM.RegDataTable> (); _dTableReg = _db.StudentRegistrations .AsEnumerable() .OrderByDescending(r => r.Id) .Select(r => new { SoftwareUsed = r.StudentRegistrationCourses .SelectMany(c => c.MultiCourse.MultiCourseDetails .Select(mc => mc.Course.Name)).Aggregate((m, n) => m + "," + n) } 不适用于空集合,因此要解决此问题,如果您需要支持空集合,请使用Aggregate,如下所示:

string.Join