c# - Datatable Comparison of - primary keys is not working -
i have written code block compares datatable scheme differences.
this code:
private static void validateschema(datatable originaltbl, datatable othertbl) { var primarykeydoesnotmatch = originaltbl.primarykey != othertbl.primarykey; if(primarykeydoesnotmatch) { throw new argumentexception("primary key not match"); } var primarykeydoesnotexist = originaltbl.primarykey == null; if(primarykeydoesnotexist) { throw new argumentexception("primary key not exist"); } var othertablehasadditionalcolumns = (from x in othertbl.columns.oftype<datacolumn>() !originaltbl.columns.oftype<datacolumn>().any(y => y.columnname == x.columnname) select x).any(); if (othertablehasadditionalcolumns) { throw new argumentexception("other table have additional columns."); } var columnsaremissinginothertable = (from x in originaltbl.columns.oftype<datacolumn>() !othertbl.columns.oftype<datacolumn>().any(y => y.columnname == x.columnname) select x).any(); if (columnsaremissinginothertable) { throw new argumentexception("other table not have columns."); } var columndatatypesdoesnotmatch = (from x in othertbl.columns.oftype<datacolumn>() originaltbl.columns.oftype<datacolumn>().any(y => x.datatype != y.datatype) select x).any(); if (columndatatypesdoesnotmatch) { throw new argumentexception("column's data type not match"); } }
i have unit test has been implemented test these scenarios.
the problem when test "columndatatypedoesnotmatch" or "columnsaremissinginothertable" runs till first if statement , tells me "primary key not match" do!
any idea why happens?
your appreciated
tanx in advance.
sure. primarykey
can never equal 1 (well, unless it's same table, or both have null
- although should still have 2 separate new datacolumn[0]
arrays), because you're performing reference comparison, , on array boot.
instead, have check example based on names of columns involved (and depending on requirements, data types well):
bool compare(datacolumn[] primary, datacolumn[] secondary) { if (primary.length != secondary.length) return false; var names = new hashset<string>(secondary.select(col => col.columnname)); return primary.all(col => names.contains(col.columnname)); }
you'll have expand required per requirements, example based on whether care case sensitivity etc.
Comments
Post a Comment