循环引用在将对象序列化为JSON时检测到异常

就像这篇文章中提到的那样,我在序列化实体框架代理时遇到了Json序列化错误:


序列化类型为'System.Data.Entity.DynamicProxies.PurchaseOrder_446B939192F161CDBC740067F174F7A6059B0F9C0EEE68CD3EBBD63CF9AF5BD0'的对象时,检测到循环引用。


但是不同之处在于,我的实体中没有循环引用,并且仅在我们的生产环境中发生。在本地,一切正常...


我的实体:


public interface IEntity

{

    Guid UniqueId { get; }

    int Id { get; }


public class Entity : IEntity

{

    public int Id { get; set; }

    public Guid UniqueId { get; set; }

}


public class PurchaseOrder : Entity

{

    public string Username { get; set; }

    public string Company { get; set; }


    public string SupplierId { get; set; }

    public string SupplierName { get; set; }


    public virtual ICollection<PurchaseOrderLine> Lines { get; set; }

}


public class PurchaseOrderLine : Entity

{

    public string Code { get; set; }

    public string Name { get; set; }

    public decimal Quantity { get; set; }

}

我的PurchaseOrderController上的GetCurrent操作引发异常:


public class PurchaseOrderController : Controller

{

    private readonly IUnitOfWork _unitOfWork;


    public PurchaseOrderController(IUnitOfWork unitOfWork)

    {

        _unitOfWork = unitOfWork;

    }


    public JsonResult GetCurrent()

    {

        return Json(EnsurePurchaseOrder(), JsonRequestBehavior.AllowGet);

    }


    private PurchaseOrder EnsurePurchaseOrder()

    {

        var company = RouteData.GetRequiredString("company");

        var repository = _unitOfWork.GetRepository<PurchaseOrder>();


        var purchaseOrder = repository

                .Include(p => p.Lines)

                .FirstOrDefault

                (

                    p => p.Company == company && 

                         p.Username == User.Identity.Name

                );


        if (purchaseOrder == null)

        {

            purchaseOrder = repository.Create();

            purchaseOrder.UniqueId = Guid.NewGuid();

            purchaseOrder.Company = company;

            purchaseOrder.Username = User.Identity.Name;

            _unitOfWork.SaveChanges();

        }


        return purchaseOrder;

    }

}


蛊毒传说
浏览 606回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP