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

问题描述 投票:0回答:1

我具有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;
}

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

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

c# asp.net linq-to-sql asmx
1个回答
0
投票

[循环引用表示您有一个对象a,它引用了b(例如a.B = b),但以某种方式b引用了a的后缀(如b.A = a)。

[不幸的是,并非两个对象都指向另一个对象。导致圆度的链可以更长(例如product指向另一个product指向department并指向product)。

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

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

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

[WebMethod] public List<ProductDTO> GetData(int companyId, int custId) { return ProductService.GetCompanyData(companyId, custId).ToDTO(); }

© www.soinside.com 2019 - 2024. All rights reserved.