json - WCF 通过使用 Entity Framework Complex 返回 JSON

标签 json entity-framework serialization wcf-rest

最近我使用 EF4 设置了一个 WCF Restful 服务。 返回 XML 格式响应时,一切都解决了。然而,当涉及到 JSON 时,我得到了 504 错误。 unable to return json data, WCF Resful Service .NET 4.0

通过使用 Service Trace Viewer 进行更深入的挖掘: 我发现了这个错误:

'The type 'xxx.DataEntity.AppView' 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.'

“AppView”是一个复杂的对象类,由 EF4 从存储过程生成。 我花了很多时间在谷歌上搜索如何禁用 IsReference,但目前收效甚微。

有人吗?有什么解决办法吗?

提前致谢

代码:

[OperationContract]
        [WebInvoke(Method = "GET",
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "App/{id}/{format}")]
        AppView FuncDetail(string id, string format);



public AppView FuncDetail(string id, string format)
        {
            SetResponseFormat(format);
            return AppSvcs.GetById(id);
        }


private void SetResponseFormat(string format)
            {
                if (format.ToLower() == "json")
                {
                    ResponseContext.Format = WebMessageFormat.Json;
                }
                else
                {
                    ResponseContext.Format = WebMessageFormat.Xml;
                }
            }

最佳答案

我遇到了完全相同的问题。它只发生在我试图返回 JSON 序列化实体对象的服务方法中。对于我的所有其他方法,我返回 JSON 序列化数据传输对象 (DTO),它们是独立的并且未连接到 Entity Framework 。我正在使用 DTO 将数据发布到方法中。通常,您发送的数据不需要您存储在模型或数据库中的所有数据,例如ID 值、更新日期等。映射在模型类中完成,如下所示:

public partial class Location
{

    public static LocationDto CreateLocationDto(Location location)
    {
        LocationDto dto = new LocationDto
        {
            Accuracy = location.Accuracy,
            Altitude = location.Altitude,
            Bearing = location.Bearing                
        };
        return dto;
    }

它可能看起来有点笨拙,但它确实有效,它确保您只发送您打算发回的数据字段。它对我有用,因为我只有 5 或 6 个实体,但我可以看到,如果你有很多类,它会变得有点乏味。

关于json - WCF 通过使用 Entity Framework Complex 返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4321118/

相关文章:

json - 服务器上的JSON.parse错误,但本地主机上没有

entity-framework - EF 4.1模型第一个代码生成工具或模板

c# - 无法翻译 LINQ 表达式

java - 在运行时设置序列化属性

java - 支持对象版本的 Java 序列化库

java - 如何使用 Feign 框架添加 JSON 形式的 URL 参数?

java - 使用 Java POST 请求在 Django Tastypie 上创建资源,但收到 500 错误代码

Python Json 配置 'Extended Interpolation'

sql-server - Entity Framework ,查看而不是插入触发器。无法在 View 中插入一行

javascript 从解析的对象中调用 Json Parse