带有链接表的ASMX的循环引用错误

我在Web应用程序中具有ASMX service的以下代码。尝试获取XML格式的数据。为了清楚起见,我删除了一些数据

    /// <summary>
    /// Summary description for CompanyServices
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script,using ASP.NET AJAX,uncomment the following line. 
    // [system.web.Script.Services.scriptservice]
    public class CompanyServices: system.web.Services.WebService
    {
        [WebMethod]
        public List<Product> GetData(int companyId,int custId)
        {
          return ProductService.getcompanyData(companyId,custId).ToList();
        }

在调试模式下所有运行,但我不断收到错误消息

System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: A circular reference was detected while serializing an object of type Company

所以我创建了相同的类型,并且围绕它的每个循环都使用了类似的

foreach (Product p in ProductService.getcompanyData(companyId,custId).ToList())
{
  Product newProd = new Product
  newProd.Name = p.Name;
  newProd.Department = p.Department;
}

这一直有效,直到我添加了Department,该部门已链接到另一个表(部门)

在Google周围四处搜寻,但不知道是什么原因引起的或如何解决?

dalaoer007 回答:带有链接表的ASMX的循环引用错误

循环引用意味着您有一个对象a引用了b(例如a.B = b),但又以某种方式b引用了a回来了(例如{{1} })。

不幸的是,并非两个对象都指向另一个对象。导致循环性的链可以更长(例如b.A = a指向另一个product指向product并指向department)。

大多数时候,根本原因是您的服务公开了使用父子关系连接的原始Entity Framework(或其他ORM)对象。因为ORM导航属性是延迟加载的,所以只要您拥有product,它就有它的父级(例如product),但是product.Department具有department属性,它指向产品其中一种产品就是您刚开始就已经访问过的产品。有你的周期。

解决方案是创建另一类DTO类,在其中仅维护单向导航属性。因此,例如,Products有其父级ProductDTO,但是DepartmentDTO故意缺少 DepartmentDTO属性。

这样,跟随您的导航属性的序列化程序会在某个时间点停止,因为没有循环。您的服务公开了这些DTO类

IEnumerable<ProductDTO> Products
本文链接:https://www.f2er.com/2521096.html

大家都在问