开发者

How do I add a column into a data set loaded with an outdated schema in C#?

Background

Here is my issue. Earlier in the course of my program a System.Data.DataSet was serialized out to a file. Then sometime later the data set schema was changed in the program, specifically a column was added to one of the tables.

This data set has been created using VS and C#, so it has all the properties able to access the rows and columns by name (through the Microsoft generated code). It has all the files (.xsd, .cs, etc.) that VS needs to know what the data set looks like and the names therein.

The file is loaded and saved through XML Serialization. This causes an issue now because when I deserialize the old file it loads in the data related to the old schema. This works for the most part, but the object that is created (the data set) has everything but the column that was added later. So, when trying to access the new column it fails because the deserialization did not know about 开发者_StackOverflow中文版it and the entire column winds up being null.

This now causes more issues because it throws an exception when trying to access that column (because it's null) through the properties of the data set.

Question

My question is, can I somehow add in the column after deserialization? I apparently need to add it so that it complies with the Microsoft generated code because doing this:

myDataSet.myTable.Columns.Add("MyMissingColumn");

...does not add the column it needs. It may add a column, but the row property myDataRow.MyMissingColumn returns null and errors out.

Do I need to somehow copy the new schema into this object? Again, the only reason this is failing is because the old file was serialized using the old schema.

Any suggestions are appreciated.


Why don't you load the schema from the new schema file, and then load the old data. Provided your column allows nulls it should be fine.

DataSet data = new DataSet();
data.ReadXmlSchema(schemaFile);
data.ReadXml(dataFile, XmlReadMode.IgnoreSchema);

Otherwise just add it on the fly:

 if (!data.Tables[0].Columns.Contains("SomeId"))
 {
    var column = new DataColumn("SomeId", typeof(int));
    // give it a default value if you don't want null
    column.DefaultValue = 1;
    // should it support null values?
    column.AllowDBNull = false;
    data.Tables[0].Columns.Add(column);
 }


you are adding a new column without specify its data type, strange, I would specify typeof(string) using another overload of the Add.

beside this, it's understandable that you cannot do: myDataRow.MyMissingColumn because there was no type/column mapping in the initial version of the XSD, but can you anyway access to this column by name or index?

try something like this

myDataRow["MyMissingColumn"] = "Test";

var s = myDataRow["MyMissingColumn"].ToString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜