我試圖序列化EF 4 STE圖時遇到了一個非常有趣的異常。EF DataContractSerializer異常
System.IndexOutOfRangeException was caught
Message=Index was outside the bounds of the array.
Source=mscorlib
StackTrace:
Server stack trace:
at System.Runtime.Serialization.ObjectReferenceStack.EnsureSetAsIsReference(Object obj)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.OnHandleIsReference(XmlWriterDelegator xmlWriter, DataContract contract, Object obj)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
...
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter writer, Object graph)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(Stream stream, Object graph)
我的序列化代碼是相當簡單:
using (MemoryStream memoryStream = new MemoryStream())
{
DataContractSerializer dc = new DataContractSerializer(data.GetType());
dc.WriteObject(memoryStream, data);
memoryStream.Flush();
memoryStream.Position = 0;
StreamReader reader = new StreamReader(memoryStream);
var serializedObject = reader.ReadToEnd();
}
在我的對象圖,我已經添加了幾個孩子實體父實體,而且我發現,如果我打電話。父母上的AcceptChanges()擴展方法,一切都很順利。
有沒有其他人遇到過這樣的事情?什麼可能導致它?任何想法如何我可以追究罪魁禍首?
更新:我發現一個link其他人有類似的問題。他們說,System.Runtime.Serialization.ObjectReferenceStack.EnsureSetAsIsReference)正在進行一些循環驗證,可能會發現問題。
更新2:我還發現在DataContractSerializer的構造函數中將preserveObjectReferences設置爲true會清除異常。
更新3:使用this article中描述的方法結束調用帶有preserveObjectReferences設置爲true的重載DataContractSerializer構造函數。雖然我仍然不能解釋它...
因此,也許現在,我的問題變成:DataContractSerializer上的preserveObjectReferences與所有STE的?
謝謝!