Cannot serialize a DataTable that is part of a DataSet

I have a DataSet with some DataTables. I can binary serialize a DataSet successfully.

If I try to serialize one of the DataTables separately, I get a NullReferenceException.

If I make a copy of the DataTable, then copying will be fine.

Does anyone know what I'm doing wrong?

This code reproduces the problem:

internal class Program { private static void Main(string[] args) { System.String xml = "<CR><AN>543</AN><Br>XYZ</Br><Id>888</Id><M>123456</M><EVT>DATA</EVT><data><telephony><S>2012-01-11T14:01:54.9571247Z</S><CID>100000</CID><reason>test</reason></telephony></data></CR>"; var ds = new System.Data.DataSet(); using (var stringReader = new System.IO.StringReader(xml)) { ds.ReadXml(stringReader); } //This works. var serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); using (var memStream = new System.IO.MemoryStream()) { serializer.Serialize(memStream, ds); } System.Data.DataTable dt0 = ds.Tables[0]; //Serializing a copy works System.Data.DataTable copy = dt0.Copy(); using (var memStream = new System.IO.MemoryStream()) { serializer.Serialize(memStream, copy); } //Serializing the original fails with a NULL Reference Exception using (var memStream = new System.IO.MemoryStream()) { serializer.Serialize(memStream, dt0); } } } 
+4
source share
2 answers

IMO this is a mistake. I will call the serializing dataset as case A, which can be considered as case B and copy the datatable case C

Your deserialized dataset has two tables CR and data with a relationship between them. In case B, the internal elements lose some information about the data table (more precisely, the collection of rowsOrder ).

Failure Sequence:

  • the inner class NewDiffgramGen supports row ordering:
    • all tables in the data set (case A)
    • one table provided (case B)
    • one table provided (register C)
  • XmlDataTreeWriter inner class serializes DataRows recursively through child relations, they are cleared during copying in case of C
  • in case B XmlDataTreeWriter fails on this.rowsOrder[row].ToString() and throws a NullReferenceException

So, you have three options:

  • serialize the entire data set
  • clear dt0.ChildRelations
  • serialize copy
+2
source

dt0.Copy() does not copy exactly the same object as dt0 . I debugged your code, and the copy object did not contain an instance of the DataSet . So, if you need to serialize a DataTable , perhaps serializing a copy is the best option.

-2
source

All Articles