2017-05-20 30 views
0

我有一個SQL數據庫表,它連接了另外兩個表。如何將集合中的哈希集合正確地導出到XML

課程(表1),學生(表2)

連接表被稱爲StudentCourses樣子: 複合主鍵由2列:StudentIDCourseID

當我加入我的數據庫通過EDMX到我的C#項目,這個連接表不會被添加。在我的程序結束之前這是OK的,我需要將所有數據導出到XML中,其中包括一個名爲StudentCourses.xml的XML文件。

我可以通過course.Students屬性(一個hashset)訪問每個課程的學生列表,我可以通過使用student.Courses屬性(也可以是hashset)訪問每個學生的課程列表。

我想窩在出口過程中的學生名單與foreach loop,但它是不允許的:

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)))); 

什麼是訪問hashset對該出口到XML的最佳方式辦法?

+0

您是否試圖用'sc.Students'中的學生'替換'foreach(sc學生中的var學生)''? –

+0

xml中的根元素不能是數組。所以簡單地創建一個根元素並將你的數組放入根中。 XElement root = new XElement(「root」); root.Add( 「documentStudentCourses」); – jdweng

+1

謝謝大家的評論! – zig

回答

0

我相信你想要的是以下內容。

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)) 
    ) 
); 

但它沒有什麼比Hashsets更多的任何其他類型的eumerable。

+0

這正是我所需要的。我真的很難找出如何在這種情況下編寫語法。非常感謝! – zig