Linq To Sql objects and Serialization issue

I am trying to serialize an object graph. It works up until I have to load a child entity that is an entity set. The system won't allow it to serialize... it gives me this error:

Type 'System.Data.Linq.EntitySet`1[NetDataContractSerializerTest.JobService]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types.

Here is the code I am using:

        DataClasses1DataContext dataAccessContext = new DataClasses1DataContext();
        MemoryStream stream = new MemoryStream();

        DataLoadOptions dataloadOptions = new DataLoadOptions();
        dataloadOptions.LoadWith<JN>(j => j.nh);  
        dataloadOptions.LoadWith<JN>(j => j.JobServices);// this is the child entity set

        dataAccessContext.LoadOptions = dataloadOptions;

        var jn= dataAccessContext.JN.Where(j => j.LocnID.Trim() == "HT").ToList();
        var netDataContractSerializer = new NetDataContractSerializer();
        netDataContractSerializer.Serialize(stream, jn); //the error happens here

If I remove the

dataloadOptions.LoadWith(j => j.JobServices)

the data will serialize with the JN and nh tables intact. But when I put

dataloadOptions.LoadWith(j => j.JobServices)

back in I get the error.

I personally think that it wants me to add a ToList() to the JobServices, unfortunately I can't do

dataloadOptions.LoadWith(j => j.JobServices.ToList())

This throws an error.

Any ideas?

Answers


The error message is very informative: the JobService class is not marked to be serialized as a data contract.

You'll need to decorate it with the DataContractAttribute attribute, and decorate the members with DataMember attribute.

[DataContract]
public class JobService
{
     [DataMember]
     public string SomeProperty { get; set;}

}

Well well well.... look what I found..... This seemed to serialize and deserialize my stuff just fine. Instead of using NetDataContractSerializer.Serialize() to it, this guy wrote serialize and deserialize functions that used DataContractSerializer, XMLWriter and XMLReader

Check the link below

http://www.codeproject.com/Tips/47054/How-to-serialize-list-of-linq-entities-ex-from-DBM


Need Your Help

Action Script 3. Timer MM:SS doesn't work

actionscript-3 flash actionscript time timer

I'm creating app and I need to show game time MM:SS format. But I don't know why timer doesn't wrok It shows 0:00.359 (359 of miliseconds) and not change. Where is the problem? I can't find It. Thank

Recognize only one gesture at a time

ios cocoa-touch gesture

I need to recognise only one gesture at a time in my app.