我具有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周围搜索,但不知道是什么原因引起的或如何解决?
[循环引用表示您有一个对象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
属性。
[WebMethod]
public List<ProductDTO> GetData(int companyId, int custId)
{
return ProductService.GetCompanyData(companyId, custId).ToDTO();
}