开发者

Entity framework serialize POCO to JSON

开发者 https://www.devze.com 2023-03-31 19:22 出处:网络
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 collec

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; }
}


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


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.


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
{
}


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号