1

I'd like to serialize my linq object to json. The linq object is disconnected, meaning the datacontext was disposed long time ago. There are "related" objects which were not loaded during the object load process which can't be accessed (When accessed, runtime error return "Cannot access a disposed object." because the datacontext is gone)

Is there any json/xml converter with the ability to serialize this object? I don't want to chanage the dbml

Is there any serialization object with the ability to configure ignore exception properties or so?

To reproduce that issue, create this object:

public class HelpMeToSerialize
{
    public string Name;
    public int Age
    {
        get
        {
            throw new Exception("Can't access this on runtime");
        }
        set
        {
        }
    }

}

And simply serialize it with this code or any other code you have:

        HelpMeToSerialize obj = new HelpMeToSerialize();
        System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(obj.GetType());
        x.Serialize(Console.Out, obj);
1
  • You should use separate ViewModels. Commented Oct 23, 2011 at 13:54

2 Answers 2

3

If your Linq generated object has a relationship to another table, which you did not load at the time of creating the object (via Linq2Sql for example), then you can do the following to serialize it:

//assume that your linq created object with class type StronglyTypedLinqObject has a field, ID, and a relationship called RelatedThing

StronglyTypedLinqObject row_from_db = null;

using(var myDatabase = new MyLinqContext(ConnectionString))
{
    myDatabase.DeferredLoadingEnabled = false; 

   //assume this pulls one item back which has a relationship
   row_from_db = (from o in myDatabase.TheTableToSelectFrom select o).Single();
   row_from_db.RelatedThing = null; //this line may be unnecessary
} // context is disposed now
return Json(row_from_db); //this call should succeed

If you disable deferred loading and try to serialize then it won't try to lazy load the related objects.

Hope that works.
Mustafa

Sign up to request clarification or add additional context in comments.

Comments

0

The DataContractSerializer for XML and DataContractJsonSerializer for JSON. You could also try the NewtonSoft JSON library.

1 Comment

Both DataContractJsonSerializer and NewtonSoft JSON library failed. The return is System.ObjectDisposedException: Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.