0

I get the following error when trying to add a datacolumn to a datatable: Cannot add a nested relation or an element column to a table containing a SimpleContent column. This happens when I hit this code the first time mt.Columns.Add("IdentityId", typeof(int));

The odd thing is that, when I view the datatable in the debugger after the previous error, the column is there. When I hit to continue, the error is: A column named 'IdentityId' already belongs to this DataTable. It seems that it adds it, and then generates the error.

Here's the code:

XElement doc = XElement.Load(XmlFileName);
string TextToFind = "Some Text";
IEnumerable<XElement> query1 = doc.Descendants("desc").Where(c => c.Value == TextToFind).Ancestors("re");
IEnumerable<XElement> query2 = query1.First().Parent.ElementsAfterSelf("ti");
string xml = query2.First().ToString();
stream = new StringReader(xml);
reader = new XmlTextReader(stream);
xmlDataset.ReadXml(reader);
DataTable mt = xmlDataset.Tables["mt"];
DataColumn dc = mt.Columns.Add("IdentityId", typeof(int));
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;

I know it has something to do with the fact that the datatable comes from XML, and the few solutions I have found deal more with the xml than with the datatable. The XML cannot be changed.

Joe_Hendricks
  • 746
  • 4
  • 16

1 Answers1

0

Since there was no help, I ended up copying with traditional loops. I tried to use Copy and Close, but I kept receiving the same error. MSDN was able to guide me through a solution:

private DataTable ConvertToRegularDataTable(DataTable source)
{
    DataTable result = new DataTable();

    foreach (DataColumn c in source.Columns)
    {
        result.Columns.Add(c.ColumnName, typeof(string));
    }
    DataColumn dc = new DataColumn("ID"); // table.Columns.Add("IdentityId", typeof(int));
    dc.AutoIncrement = true;
    dc.AutoIncrementSeed = 1;
    dc.AutoIncrementStep = 1;
    result.Columns.Add(dc);

    foreach (DataRow dr in source.Rows) 
    {
        result.Rows.Add(dr.ItemArray);
    }
    return result;
}
Joe_Hendricks
  • 746
  • 4
  • 16