Cannot be serialized to JSON because its IsReference setting is 'True'


Issue:

{"The type 'XXXXXXXXXX' cannot be serialized to JSON because its IsReference setting is 'True'. The JSON format does not support references because there is no standardized format for representing references. To enable serialization, disable the IsReference setting on the type or an appropriate parent class of the type."}

Solution:

http://blogs.microsoft.co.il/blogs/idof/archive/2008/09/30/serializing-entity-framework-object-to-json.aspx

DataContractJsonSerializer

EF objects are marked with IsReference=true and therefore cannot be serialized with DataContractJsonSerializer.

Trying to serialize EF objects with that serializer throws the following exception:
"The type 'xxx' cannot be serialized to JSON because its IsReference setting is 'True'. The JSON format does not support references because there is no standardized format for representing references. To enable serialization, disable the IsReference setting on the type or an appropriate parent class of the type."

BTW, that message is somehow misleading because you cannot "disable" the IsReference setting because all EF objects inherit from the EntityObject class which is also marked with IsReference=true

JavaScriptSerializer

According to MS connect, we should be able to use AJAX's JavaScriptSerializer to serialize EF objects, but trying so raises the following exception:
"A circular reference was detected while serializing an object of type 'XXX'."

The circular reference exception will be raised when a navigable relation is double-sided (can access both sides of the relation), so the first thing to do is disable one side of the relation.

The exception will also be thrown when you use 1:1 relations (or 1:0..1 or any relation causing the creation of an EntityReference type property), in this case the exception will be of type ''System.Data.Metadata.Edm.AssociationType'.

The solution to this is to make the serializer ignore the properties of type EntityReference, using an empty implementation of a class deriving from JavaScriptConverter and registering it using the RegisterConverters method of the JavaScriptSerializer object.

So to conclude, serializing EF object to JSON is not quite of an easy task. There is, however, another solution to serialize EF objects, using the JSON serializer supplied with Ado.Net Data Services (Astoria), the catch is that the JSON serializer is an internal serializer, which means you'll have to expose the EF as a Data Service, making this solution a bit annoying.

优质内容筛选与推荐>>
1、现代软件工程课程作业 第一章第11题
2、由count(sno)和count(cno)引发的思考
3、pip_install的安装
4、十字链表的应用
5、正则表达式


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号