簡體   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