将实体框架对象序列化为 JSON [英] Serialize Entity Framework objects into JSON

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

问题描述

使用 WCF 的本机 DataContractJsonSerializer 或 ASP.NET 的本机 JavaScript 序列化程序似乎无法将实体框架对象序列化为 JSON.这是由于两个序列化程序都拒绝引用计数问题.我也试过 Json.NET,它也特别在引用计数上失败问题.

It seems that serializing Entity Framework objects into JSON is not possible using either WCF's native DataContractJsonSerializer or ASP.NET's native JavaScript serializer. This is due to the reference counting issues both serializers reject. I have also tried Json.NET, which also fails specifically on a Reference Counting issue.

Json.NET 现在可以序列化和反序列化实体框架实体.

Json.NET can now serialize and deserialize Entity Framework entities.

我的对象是实体框架对象,它们被重载以执行额外的业务功能(例如身份验证等),我不想用特定于平台的属性等来装饰这些类,因为我想展示一个平台- 不可知的 API.

My objects are Entity Framework objects, which are overloaded to perform additional business functionality (eg. authentication, etc.) and I do not want to decorate these classes with platform-specific attributes, etc. as I want to present a platform-agnostic API.

我实际上已经在 https://blog.programx.co.uk/2009/03/18/wcf-json-serialization-woes-and-a-solution/

我是否遗漏了一些明显的东西?

Have I missed something obvious?

推荐答案

我这样做的方法是将我想要序列化的数据投影到一个匿名类型中并对其进行序列化.这确保只有我在 JSON 中真正想要的信息才会被序列化,并且我不会无意中序列化对象图更下方的某些内容.它看起来像这样:

The way I do this is by projecting the data I want to serialize into an anonymous type and serializing that. This ensures that only the information I actually want in the JSON is serialized, and I don't inadvertently serialize something further down the object graph. It looks like this:

var records = from entity in context.Entities
              select new 
              {
                  Prop1 = entity.Prop1,
                  Prop2 = entity.Prop2,
                  ChildProp = entity.Child.Prop
              }
return Json(records);

我发现匿名类型非常适合于此.显然,JSON 并不关心用于生成它的类型.匿名类型让您可以完全灵活地将哪些属性和结构放入 JSON.

I find anonymous types just about ideal for this. The JSON, obviously, doesn't care what type was used to produce it. And anonymous types give you complete flexibility as to what properties and structure you put into the JSON.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆