Search code examples
c#xmledmx

How to export a hashset inside a collection to XML properly


I have a SQL database table which joins two other tables.

Courses (Table 1), Students (Table 2)

The joined table is called StudentCourses looks like: Composite Primary Key made up of 2 columns: StudentID, CourseID

When I add my database to my C# project through EDMX, this joined table does not get added. This is OK until the end of my program, where I need to export all the data to XML, including an XML file called StudentCourses.xml.

I can access each course's list of students by using course.Students property (a hashset), and I can access each student's list of courses by using student.Courses property (also a hashset).

I'm trying to nest the list of students within the export process with a foreach loop, but it is not allowed:

XDocument documentStudentCourses = new XDocument(
          new XDeclaration("1.0", "utf-8", "yes"),
          new XComment("Contents of StudentCourses table in CourseroomScheduler database"),
          new XElement("StudentCourses",
          from c in CoursesCollection // a List<Course> object
          select new XElement("Course",
          foreach (var student in sc.Students) { new XElement("StudentID", student.StudentID); }, // this is not allowed
          new XElement("CourseID", sc.CourseID))));

What is the best way to access the hashset for exporting to XML in this way?


Solution

  • I believe what you want is the following.

    var studentCourses = new XDocument(
        new XDeclaration("1.0", "utf-8", "yes"),
        new XComment("Contents of StudentCourses table in CourseroomScheduler database"),
        new XElement("StudentCourses",
            from c in CoursesCollection
            select new XElement("Course", from student in c.Students
                                          select new XElement("StudentID", student.StudentID))
        )
    );
    

    but it has nothing more to do with Hashsets than any other kind of eumerable.