实体框架将POCO序列化为JSON

实体框架将POCO序列化为JSON

本文介绍了实体框架将POCO序列化为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ef 4.1,并且有一个POCO对象要序列化为JSON,我已经读到在使用延迟加载时这样做有问题,但是我不确定我可以这样做,因为Message可以具有Message的集合.

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.

有没有办法做到这一点?将这种对象序列化为JSON?

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

我的Message对象看起来像:

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

推荐答案

问题是循环引用.避免这种情况的一种简单方法是使用Json.Net http://james.newtonking.com /projects/json-net.aspx 而不是默认的MVC json序列化器.最新版本的Json.Net将开箱即用循环引用序列化对象. http://james.newtonking.com/projects/json/help/PreserveObjectReferences.html 有关该问题的更多信息

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

这篇关于实体框架将POCO序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:48