1

I'm using Ef 4.1 and I've got a POCO object I'd like to serialize to JSON, I've read there is a problem to do so when using lazy loading but I'm not sure I can because a Message can have a collection of Message.

Is there any way to do this? sirialize this kind of object into JSON?

My Message object looks like:

public class Message
{
    [Key]
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public DateTime CreatedAt { get; set; }
    public DateTime? LastModified { get; set; }

    public virtual User User { get; set; }

    public virtual Message Parent { get; set; }

    public virtual ICollection<Message> Children { get; set; }
}
skaffman
  • 398,947
  • 96
  • 818
  • 769
CD..
  • 72,281
  • 25
  • 154
  • 163

4 Answers4

2

The problem is circular references. An easy way to avoid this is to use Json.Net http://james.newtonking.com/projects/json-net.aspx instead of the default MVC json serializer. The latest version of Json.Net will serialize objects with circular references out of the box. http://james.newtonking.com/projects/json/help/PreserveObjectReferences.html for more info on the problem

Bobby Richard
  • 618
  • 5
  • 13
  • Thanks! `ReferenceLoopHandling.Ignore` and a custom `ContractResolver` did the trick :-) – CD.. Aug 30 '11 at 06:35
1

Eager load it using Include(). Sample linq:

var serializeMe = (from m in MyContext.Message.Include("User") where m.Id == someValue select m).ToList();

That will tell EF to load the User navigation property right away instead of lazy loading it, and the serializer should have no problem with it then.

Tridus
  • 5,021
  • 1
  • 19
  • 19
  • Including the related entity solved a problem I was having serializing an EF object graph because I was able to take the virtual keyword off of the offending property in my class. Thanks! – marc Feb 15 '12 at 16:48
0

Well, lets go by parts.

¿Why is happening this?

Because you have virtual properties. If you are using EF you actually need them if you are using Lazy loading. You can configurate your EF to not do this by this example:

        context.Configuration.ProxyCreationEnabled = false;

where context is your ObjectContext or DbContext... this assuming you are using EF. But for most scenarios this is not a good aproach.

Possible Solution

As I always say: "there are not good or bad solutions, just different ways and it depends on the context", saying that, you can create dynamic objects.

In case you only have to serialize a unique object, you can do something like this

        Json(new {@property1=yourObject.property1, @property2=yourObject.property2})

In case you have a list, well, you can do this:

        var list = new List<dynamic>();

        foreach(var item in myRepository.GetAll())
        {
            list.Add(new
            {
                @property1= item.property1,
                @property2= item.property2,
                @property3= item.property3
            });
        }
        return Json(list, JsonRequestBehavior.DenyGet);

I tried to make this as generic as I can. I hope this can help somebody!!

Best regards and have a very nice day! :)

0

How about this:

  • Mark your class as [Serializable]
  • Use the JsonSerializer to serialize your object to JSON.
  • Perhaps use eager loading on the properties in your EF query?
Message msg = new Message();
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(msg.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, msg);
string json = Encoding.Default.GetString(ms.ToArray());


[Serializable]
public class Message
{
}
p.campbell
  • 98,673
  • 67
  • 256
  • 322
  • thanks for the detailed answer, but I'm afraid the virtual properties are not loaded this way... – CD.. Aug 29 '11 at 20:51
  • @CD : what am I missing? The `virtual` property serialized just fine for the collection and the single properties: http://i.imgur.com/9mkW3.png – p.campbell Aug 29 '11 at 21:03