I am trying to create XML with the following structure:
<ResponseSubschemas>
<organism>LMO</organism>
<Subschema>
<id>MLST</id>
<name>MLST</name>
<loci>
<locus>LMO0558</locus>
<locus>LMO0563</locus>
</loci>
</Subschema>
<Subschema>
<id>MLVST</id>
<name>MLVST</name>
<loci>
<locus>LMO1305</locus>
<locus>LMO1089</locus>
</loci>
</Subschema>
</ResponseSubschemas>
I have a.o. two tables in my database:
subschema
with as columns ID
and Name
subschemamembers
with as columns subschemaID
and locusID
.I have the following C# code:
XElement rootNode = new XElement("ResponseSubschemas", new XElement("organism", organismID));
DbDataReader subschemaReader = conn.Query("SELECT ID, Name FROM subschema WHERE OrganismID = ?", organismDbID);
while (subschemaReader.Read())
{
string subschemaDbID = (string)subschemaReader["ID"];
XElement subschemaNode = new XElement("Subschema",
new XElement("id", subschemaDbID),
new XElement("name", subschemaReader["Name"])
);
rootNode.Add(subschemaNode);
}
responseXml = rootNode.ToString();
Which creates the following partial XML:
<ResponseSubschemas>
<organism>LMO</organism>
<Subschema>
<id>MLST</id>
<name>MLST</name>
</Subschema>
<Subschema>
<id>MLVST</id>
<name>MLVST</name>
</Subschema>
</ResponseSubschemas>
Now I need to add for each Subschema
node a loci
node, loop over the loci and add them. I tried creating a new DbDataReader
inside the while loop, but then i got errors like: There is already an open DataReader associated with this Connection which must be closed first
. So, how do I do this?
Update:
Trying to go with the JOIN
approach, I have crafted the following SQL:
SELECT subschema.Id, subschema.name as subschemaName, locus.Name as locusName
FROM subschema
LEFT JOIN subschemamembers ON subschemamembers.SubSchemaID = subschema.PrimKey
LEFT JOIN locus ON subschemamembers.LocusID = locus.ID
WHERE subschema.OrganismID = 6
ORDER BY subschema.Id;
Which gives the following output:
Id subschemaName locusName
MLST MLST LMO0558
MLST MLST LMO0563
MLVST MLVST LMO1305
MLVST MLVST LMO1089
but I still can't figure out how I would keep track of "whether the current db row points to a different subschemaDbID".
The easy way out that will make your solution work is to enable MARS (Multiple Active Result Sets): http://technet.microsoft.com/en-us/library/ms131686.aspx
To do it without enabling MARS, you would have to make a JOIN query fetching both subschema and subschemamembers and inside your XML creation code you need to keep track of whether the current db row points to a different subschemaDbID.