类型 'Entities.Models.ConsignmentDetails' 的对象图包含循环,如果未跟踪引用,则无法序列化



检测到类型为"实体.模型.寄售详细信息"的自引用循环。路径'托运详情[0]。Consignee.ConsignmentDetails'.
我可能已经尝试过使用互联网上的每个解决方案来解决问题,无法找到我出错的地方,或者我已经搞砸了 completley
在调试我得到的是有一个无休止的循环数据,从收货人到托运货物详细信息,然后再次从收货人到托运详细信息,它继续
我无法更改我的模型类,因为我需要在获得收货人时获取托运详细信息,我还需要收货人获取托运详情

这是我的托运详情模型

namespace Entities.Models
{
//[ScriptIgnore]
[DataContract(IsReference = true)]
public partial class ConsignmentDetails
{
public int ConsignmentDetailsId { get; set; }
public int DocketNo { get; set; }
public int? ConsignmentValue { get; set; }
public int? Freight { get; set; }
public int? Aoc { get; set; }
public int? ConsigneeId { get; set; }
.
. 
public virtual Consignees Consignee { get; set; }
}
}

这是我的收货人模型

namespace Entities.Models
{
[DataContract(IsReference = true)]
public partial class Consignees
{
public int ConsigneeId { get; set; }
.
.
public virtual ICollection<ConsignmentDetails> ConsignmentDetails { get; set; }
}
}

我正在尝试做的内部控制器

public IActionResult GetConsigneeWithDetails(int id)
{
try
{
var consignee = _repository.consignees.GetConsigneesWithDetails(id);
if (consignee == null)
{
_logger.LogError($"Consignee With Id: {id} hasn't been foud inn the db");
return NotFound();
}
else
{
_logger.LogInfo($"Returned Consignee with Details for id: {id}");
var consigneeResult = _mapper.Map<ConsigneeDTO>(consignee);
JsonConvert.SerializeObject(consigneeResult);

return Ok(consigneeResult);
}
}
catch(Exception ex)
{
_logger.LogError($"SOmething Went Wrong inside GetConsigneeWithDetails action: {ex.Message}");
return StatusCode(500, "Internal Server Error");
}
}

这就是我的控制器获取数据的方式

public Consignees GetConsigneesWithDetails(int id)
{
return FindByCondition(consignee => consignee.ConsigneeId.Equals(id)).Include(d => d.ConsignmentDetails).FirstOrDefault();
}

上面的托运详情模型有 20 多个属性,我得到的响应是

{
"consigneeId": 5,
"consigneeName": "ABC",
"consigneeGstno": "AFLPG-8314-H",
"consignmentDetails": [
{
"$id": "1"
}
]
}

添加对Microsoft.AspNetCore.Mvc.NewtonsoftJson的包引用。

在您的启动中配置它.cs如下所示:

public void ConfigureServices(IServiceCollection services)
{
...
services.AddControllersWithViews()
.AddNewtonsoftJson(options=>
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
); 
...
}

最新更新