【发布时间】:2022-01-28 21:19:26
【问题描述】:
我目前正在从事一个个人项目,我想将UserTransaction 映射到GetAllTransactionRes 并在API/transaction 被击中时从我的数据库中返回所有UserTransaction。每次我使用API/transaction 端点时都会出现此错误
System.Collections.Generic.List`1[ProjectName.Modules.Transaction.Core.DTO.GetAllTransactionRes]
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.OrderedProducts.UserTransaction.OrderedProducts.UserTransaction.OrderedProducts.UserTransaction.OrderedProducts.UserTransaction.OrderedProducts.UserTransaction.OrderedProducts.UserTransaction.OrderedProducts.UserTransaction.OrderedProducts.UserTransaction.OrderedProducts.UserTransaction.OrderedProducts.UserTransaction.TransactionId.
这是UserTransaction 实体
public class UserTransaction
{
public int TransactionId { get; set; }
public DateTime Date { get; set; }
public virtual ICollection<OrderedProduct> OrderedProducts { get; set; }
}
这是Ordered Product 实体
public class OrderedProduct
{
public int Id { get; set; }
public string Product { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public bool Returned { get; set; }
public int TransactionId { get; set; }
public virtual UserTransaction UserTransaction { get; set; }
}
这是我的映射器。 GetAllTransactionRes 和 AllOrderedProductDTO 是 UserTransaction 和 OrderedProduct 实体的精确副本。
CreateMap<UserTransaction, GetAllTransactionRes>().ForMember(s => s.OrderedProducts, c => c.MapFrom(m => m.OrderedProducts));
CreateMap<OrderedProduct, AllOrderedProductDTO>();
因为我使用的是 MediatR。这是我的 GetAllTransactionQuery 的处理程序
public async Task<ICollection<GetAllTransactionRes>> Handle(GetAllTransactionQuery request, CancellationToken cancellationToken)
{
var Transactions = await _context.UserTransactions.Include(ut => ut.OrderedProducts).ToListAsync();
var mapped = _mapper.Map<ICollection<UserTransaction>, ICollection<GetAllTransactionRes>>(Transactions);
return mapped;
}
在使用 automapper 之前,我使用了来自 efcore 的 .include 方法,这给了我搜索答案时出现的相同错误,并且有人在 StackOverflow 问题中评论说我不应该直接在我的 API 中返回数据库实体。 This is the question where the said comment is posted
我做错了什么?谢谢
【问题讨论】:
标签: c# .net entity-framework-core asp.net-core-webapi automapper