繁体   English   中英

在MVC中获取“检测到自我引用循环”错误

[英]In MVC getting “Self referencing loop detected” error

我在使用MVC4Web APIAngularJS执行应用程序时遇到错误。 错误如下:

Self referencing loop detected with type 
    'System.Data.Entity.DynamicProxies.Product_259FEB40BD6111F44AA3C3CED8DD40E7E44B22CC11A32AE621E84E2239F79B2C'. Path '[0].category.products'.

模型文件夹下的我的products.cs文件是:

public partial class Product
{

    [JsonIgnore] 
    [Key]
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public Nullable<int> SupplierID { get; set; }
    public Nullable<int> CategoryID { get; set; }
    public string QuantityPerUnit { get; set; }
    public Nullable<decimal> UnitPrice { get; set; }
    public Nullable<short> UnitsInStock { get; set; }
    public Nullable<short> UnitsOnOrder { get; set; }
    public Nullable<int> ReorderLevel { get; set; }
    public bool Discontinued { get; set; }

    public virtual Category Category { get; set; }
    public virtual Supplier Supplier { get; set; }
}

产品控制器是:

public class ProductController : JsonController
{
        private readonly DBEntities _db = new DBEntities();

        public ActionResult GetProduct()
        {
            var productList = _db.Products;
            return Json(productList, JsonRequestBehavior.AllowGet);
        }
    }

返回JSON并包含在产品控制器中的类是:

public class JsonController : Controller
{
    public new ActionResult Json(object data, JsonRequestBehavior behavior)
    {
        var jsonSerializerSetting = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };

        if (Request.RequestType == WebRequestMethods.Http.Get && behavior == JsonRequestBehavior.DenyGet)
        {
            throw new InvalidOperationException("GET is not permitted for this request.");
        }
        var jsonResult = new ContentResult
        {
            Content = JsonConvert.SerializeObject(data, jsonSerializerSetting),
            ContentType = "application/json"
        };
        return jsonResult;

    }
}

使用AngularJS的productController.js文件是:

myApp.controller('productController',
['$scope', 'productDataService', '$location',
    function productController($scope, productDataService) {
        $scope.products = [];
        $scope.currentPage = 1;
        $scope.pageSize = 10;
        loadProductData();

        function loadProductData() {
            productDataService.getProducts()
                .then(function () {
                    $scope.products = productDataService.products;
                },
                    function () {
                        //Error goes here...
                    })
                    .then(function () {
                        $scope.isBusy = false;
                    });
            $scope.pageChangeHandler = function (num) {
                console.log('Product page changed to ' + num);
            }
        };
    }
]);

数据服务如下:

myApp.factory('productDataService', ['$http', '$q',
    function ($http, $q) {
        var _products = [];

        var _getProducts = function () {
            var deferred = $q.defer();
            var controllerQuery = "product/GetProduct";

            $http.get(controllerQuery)
                .then(function (result) {
                    // Successful
                    angular.copy(result.data, _products);
                    deferred.resolve();
                },
                    function (error) {
                        // Error
                        deferred.reject();
                    });
            return deferred.promise;
        };
        return {
            products: _products,
            getProducts: _getProducts
        };
    }
]);

相同类型的代码适用于另一个应用程序,但我不清楚为什么上面提到的代码不起作用。

谢天谢地,任何帮助都会被接受。

谢谢Partha

你可以这样做:

return new ContentResult
            {
                Content = JsonConvert.SerializeObject(data, Formatting.None, new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}),
                ContentType = "application/json"
            };

打开WebApiConfig并注册JsonFormatter

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
= Newtonsoft.Json.ReferenceLoopHandling.Ignore;

是的,这可能是由于json试图序列化您的导航对象。

public virtual Category Category { get; set; }
public virtual Supplier Supplier { get; set; }

1.进行任务测试以排除这种情况。

2.为它们编写一个忽略规则或为Product创建一个DTO对象,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM