For various reasons I am having to se开发者_如何学Cnd a typed dataset to a WCF service endpoint. This works fine except that upon Deserializing, the RowState of each row in each DataTable is set to 'Added', regardless of what they were on the client. If I write the serialized stream out to a file, I see that the RowState is not part of the Serialized data. How can I add this so that I can preserve the RowState across service boundaries? Not that I think it matters, but the client process is running .net 3.5 while the service process is running .net 4.0
I had this problem also, and found a very simple solution for it:
Instead of using the dataset object's "WriteXml" method, serialize the object 'manually' using a BinaryFormatter
:
BinaryFormatter bf = new BinaryFormatter();
using(FileStream fs = File.Open("datastore.dat", FileMode.Create, FileAccess.Write))
{
bf.Serialize(fs, ds);
}
When you deserialize, the object is in the exact same state as before, including the rowstate data.
Here is the code for the RowState
property:
public DataRowState RowState
{
get
{
if (this.oldRecord == this.newRecord)
{
if (this.oldRecord == -1)
{
return DataRowState.Detached;
}
if (0 < this._columns.ColumnsImplementingIChangeTrackingCount)
{
foreach (DataColumn column in this._columns.ColumnsImplementingIChangeTracking)
{
object obj2 = this[column];
if ((DBNull.Value != obj2) && ((IChangeTracking)obj2).IsChanged)
{
return DataRowState.Modified;
}
}
}
return DataRowState.Unchanged;
}
if (this.oldRecord == -1)
{
return DataRowState.Added;
}
if (this.newRecord == -1)
{
return DataRowState.Deleted;
}
return DataRowState.Modified;
}
}
as you can see, there may be nothing you can do about its value, because it is calculated rather than just stored. The easiest solution may be to just add another column to the DataSet which contains the state of the row.
(Why does it always calculate out to the value Added? Most likely because when your serialized dataset is rehydrated back on the server, new rows are created and added to the dataset - so the value is quite literally true. If you follow the above suggestion to add another column to the dataset, that will require a change to the server code to be able to examine and process it - if you are going to make that sort of change then maybe it is worth doing the whole thing and recode that service to use proper serializable DTOs instead?).
精彩评论