C# - Duplicate DataRows and all its childrows/relations

By , 11/5/2013
(0 ratings)
See title
//Assuming the first column in the datatable is the primary key, the second the foreign key

public static DataRow CopyRowAndRelations(Guid newParentGuid, ref DataRow dr)
{
	dynamic newDr = dr.Table.NewRow();

	foreach (DataColumn clm in dr.Table.Columns) {
		newDr(clm) = dr(clm);
	}

	newDr(0) = Guid.NewGuid();
	//PK
	newDr(1) = newParentGuid;
	//FK

	foreach (DataRelation rel in dr.Table.ChildRelations) {
		foreach (DataRow row in dr.GetChildRows(rel.RelationName)) {
			dynamic newRow = CopyRowAndRelations(newDr(0), ref row);

			newDr.Table.ChildRelations(rel.RelationName).ChildTable.Rows.Add(newRow);
		}
	}

	return newDr;
}

Comments

 

Log in, to comment!