序列化Linq对象不起作用

时间:2010-04-14 21:22:42

标签: asp.net vb.net linq linq-to-sql serialization

使用以下代码:

    Private Sub MakeMeSomeXmlBeforeRyanGetsAngry()

    Dim db As New MyDBDataContext

    Dim customer = From c In db.Customers Select c

    Dim dcs As New DataContractSerializer(GetType(Customer))

    Dim sb As StringBuilder = New StringBuilder
    Dim writer As XmlWriter = XmlWriter.Create(sb)
    dcs.WriteObject(writer, customer)
    Dim xml As String = sb.ToString

    Response.Write(xml)

End Sub

我正在尝试序列化我的linq客户群。但它不断投掷

  

类型'System.Data.Linq.DataQuery`1 [MyDB.Customer]'无法序列化。请考虑使用DataContractAttribute属性对其进行标记,并使用DataMemberAttribute属性标记要序列化的所有成员。有关其他受支持的类型,请参阅Microsoft .NET Framework文档。

我的问题是我已经将dbml序列化模式标记为UniDirectional,当我检查所有DataContract()>的dbml代码隐藏时。和DataMember()>元素在那里。

我不知道该怎么办。我尝试添加各种dataloadoptions并将deferredloading设置为false,但没有运气。

想法?

2 个答案:

答案 0 :(得分:2)

我认为问题出现是因为LINQ查询仅在需要时处理,并且不可序列化。尝试序列化由LINQ查询(数组,列表,单个项目等)产生的可序列化数据类型。

dcs.WriteObject(writer, customer.ToArray)

(我假设您只需序列化查询结果,而不是查询本身)

答案 1 :(得分:2)

对于我来说,将.dbml的Serialization Mode属性设置为UniDirectional:

Public Shared Function CreateXml(Of T)(ByVal item As T) As String
    Dim result As String = ""
    Dim memoryStream As New IO.MemoryStream()
    Dim serializer As New DataContractSerializer(GetType(T))
    serializer.WriteObject(memoryStream, item)
    memoryStream.Position = 0
    Using reader As New StreamReader(memoryStream)
        result = reader.ReadToEnd()
    End Using
    memoryStream.Close()
    Return result
End Function

Dim db As New SerializerDataContext()
Dim questions = db.Questions.ToList()

Dim xmlFileName As String = "D:\\xml_test.xml"
If My.Computer.FileSystem.FileExists(xmlFileName) Then My.Computer.FileSystem.DeleteFile(xmlFileName)

Dim xml As String = XmlHelper.CreateXml(Of List(Of Question))(questions)
My.Computer.FileSystem.WriteAllText(xmlFileName, xml, True)