Serializing Linq Objects Doesn't Work

Using the following code:

    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

I am trying to serialize my collection of linq clients. But he keeps throwing

The type 'System.Data.Linq.DataQuery`1 [MyDB.Customer]' cannot be serialized. Consider labeling it with the DataContractAttribute attribute and labeling all of its elements that you want to serialize with the DataMemberAttribute attribute. See the Microsoft.NET Framework documentation for other supported types.

My problem is that I already marked the Serialization dbml mode for UniDirectional, and when I check the dbml code, all the DataContract ()> and DataMember ()> elements are there.

I am not sure how to proceed. I tried to add various dataloadoptions and set the delayed load to false, but no luck.

Ideas?

+3
2

Serialization.dbml, 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)
+2

, - , LINQ . , LINQ (, , ..).

dcs.WriteObject(writer, customer.ToArray)

( , , )

+2

Source: https://habr.com/ru/post/1741170/


All Articles