You use the NextResult method in the datareader to navigate with multiple query results.
To iterate over all the data, you should do something like this:
var moreResults = true; while (moreResults) { while (reader.Read()) { ... } moreResults = reader.NextResult(); }
Thus, in this case, as a background and provided that the main set of results will be the first, filling in the main and detailed objects can be performed as follows:
First create a master record dictionary:
var masters = new Dictionary<int, Master>(); var idOrdinal = reader.GetOrdinal("id"); while (reader.Read()) { var id = reader.GetInt32(idOrdinal); masters.Add(id, new Master{Id=id, ....}); }
Then go to the detailed records and add them to the appropriate wizard:
reader.NextResult(); var masterIdOrdinal = reader.GetOrdinal("masterId"); while (reader.Read()) { var masterId = reader.GetInt32(masterIdOrdinal); var master = masters[masterId]; master.Details.Add(new Detail{....}); }
Obviously, you should replace the column names with what you have in your data, and provide full initialization of the Master and Detail objects. If the result set of details is sorted by the main identifier, the last cycle can only be optimized in order to search for only one master from the dictionary. If the end points are small, then the gain will not be so large.
Peter Lillevold
source share