[英]How to deal with DBNull in DataContractSerializer?
我有以下C#代碼
using System.Runtime.Serialization;
using System.IO;
using System.Data;
// create a datatable with two columns [c1] and [c2]
var dt = new System.Data.DataTable("MyTable");
dt.Columns.Add(new DataColumn("c1", typeof(System.Int32)));
dt.Columns.Add(new DataColumn("c2", typeof(System.String)));
//create a new and populate it
var dr = dt.NewRow();
dr["c1"] = 1;
//dr["c2"]="hello"; //purposely commented out, if not, there is NO error
dt.Rows.Add(dr);
var s = new System.Runtime.Serialization.DataContractSerializer(typeof(object[]));
var mem = new MemoryStream();
// the following line will report error
s.WriteObject(mem, dt.Rows[0].ItemArray);
// other lines ... which have nothing to do with this question
如果我不填充列[c2],則表示此數據行中有DBNull值,那么在嘗試運行s.WriteObject()時會遇到錯誤。
錯誤:
不應使用數據合同名稱為“ DBNull的類型”“ System.DBNull”: http : //schemas.datacontract.org/2004/07/System 。 如果您正在使用DataContractSerializer或將任何不是靜態已知的類型添加到已知類型的列表中,請考慮使用DataContractResolver-例如,通過使用KnownTypeAttribute屬性或將它們添加到傳遞給序列化程序的已知類型的列表中。
但是根據MS文檔“ 數據合同序列化程序支持的類型 ”
DBNull類型以特殊方式處理。 它是單例類型,並且在反序列化時,解串器會遵守單例約束並將所有DBNull引用都指向單例實例。 因為DBNull是可序列化的類型 ,所以它需要SerializationFormatter權限。
DBNull似乎是受支持的類型,我在這里真的很困惑。 請任何一位大師分享幾個燈? 比如我該怎么辦?
我知道我可以掃描所有表行並查找列值是否等於DBNull.Value,如果是,我為此列設置一個空字符串或其他內容,但這不是我想要的,因為這將“篡改” DataTable值。
在此先感謝您的幫助 !
將DBNull添加到knownTypes
列表
var s = new DataContractSerializer(typeof(object[]), new [] { typeof(DBNull) });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.