“检测到自参考循环" JSON.Net异常 [英] "Self Referencing Loop Detected" exception with JSON.Net

查看:153
本文介绍了“检测到自参考循环" JSON.Net异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以将Route对象的列表发送到我的视图(ASP.Net MVC):

I have this bit of code to send a List of Route objects to my View (ASP.Net MVC):

public ActionResult getRouteFromPart(int partId)
{
    List<Route> routes = _routeService.GetRouteByPartType(partId);

    if (routes == null)
    {
        return this.AdvancedJsonResult(null, JsonRequestBehavior.AllowGet);
    }

    return this.AdvancedJsonResult(new
    {
        Routes = routes
    }, JsonRequestBehavior.AllowGet);
}

但是我的AdvancedJsonResult类中出现了一个异常:

But I'm getting an exception here in my AdvancedJsonResult class:

if (Data != null)
{
    var settings = new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };

    string result = JsonConvert.SerializeObject(this.Data, this.Formatting, settings);
    response.Write(result);
}

我已经尝试过"ReferenceLoopHanding.Ignore"技巧,该技巧可以使异常静音,但是列表仍不会传递给视图.

I've tried the "ReferenceLoopHanding.Ignore" trick which silences the exception, but the list still doesn't get passed to the view.

当我将routes更改为单个对象而不是列表时,该代码起作用了,所以我认为代码只是不喜欢使用列表.

The code works when I change routes to a single object instead of a list, so I think the code just doesn't like working with a list.

我是这个项目的新手,所以我不确定如何解决此问题,并乐于使用列表...

I'm new to this project so I'm not sure how to fix this and make it happy with using a List...

这是完整的异常"消息,发生在string result = JsonConvert...行上.

Here's the full Exception message, which happens on the string result = JsonConvert... line.

检测到类型为'System.Data.Entity.DynamicProxies.PartNumber_B135A5D16403B760C3591872ED4C98A25643FD10B51246A690C2F2D977973452'的自引用循环.路径"routes [0] .incomingLots [0] .partNumber.partType.partNumbers".

Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.PartNumber_B135A5D16403B760C3591872ED4C98A25643FD10B51246A690C2F2D977973452'. Path 'routes[0].incomingLots[0].partNumber.partType.partNumbers'.

推荐答案

错误消息的含义是存在一个自引用循环.您必须将数据库上下文设置为在请求某些实体时不希望获取所有链接的实体.可以通过在DbContext类构造函数中添加两行以禁用自引用循环来完成此操作,如下所示:

The meaning of the error message is that there is a self referencing loop. You have to set the db context that you do not want to get all linked entities when you request some entities. It can be done by adding two lines into DbContext class constructor to disable self referencing loop as shown below:

public YourDbContext() : base("name = YourDbContext")
{       
    //add these lines in order to avoid from "Self referencing loop detected for ..." error
    this.Configuration.LazyLoadingEnabled = false;
    this.Configuration.ProxyCreationEnabled = false;
}

希望这对您有帮助...

Hope this helps...

这篇关于“检测到自参考循环" JSON.Net异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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