我有一个包含学生信息的大型 XML 提要。
<students>
<student>
<studentId>10</studentId>
<name>Joe Doe</name>
<location>Main street</location>
<studyId>1001</studyId>
<study>Business 101</study>
</student>
<student>
<studentId>255</studentId>
<name>Max Friedman</name>
<location>Main street</location>
<studyId>223</studyId>
<study>Computer Science</study>
</student>
<student>
<studentId>452</studentId>
<name>Josephine Smith</name>
<location>Clinton Dr.</location>
<studyId>881</studyId>
<study>English Literature</study>
</student>
... (2000 more rows)
</students>
我想将此信息存储在3 个单独的模型中,但我不想多次解析 XML。
型号:
public class Student
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long StudentId { get; set; } // Use the Id from the feed
public string Name { get; set; }
public long StudyId { get; set; }
[ForeignKey("StudyId")]
public virtual Study Study { get; set; }
}
public class Study
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long StudyId { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Location
{
public long LocationId { get; set; }
public string Name { get; set; }
public virtual ICollection<Study> Studies { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
我尝试了不同的方法来做到这一点,但每次它都以混乱、丑陋和完全意大利面条式的代码结束。
在伪代码中,我做了以下事情:
For each student in the XML
Create a new Student object
Check if the Location object already exists in the DB
If not, create the Location object
Add the Location object to the Student object
etc... etc...
Persist the ICollection of Students to the db
如何用最少的代码完成我想要的?