【问题标题】:A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth [duplicate]检测到不支持的可能对象循环。这可能是由于循环或对象深度[重复]
【发布时间】:2020-07-26 06:08:35
【问题描述】:

我有 2 张桌子。

产品和类别。

类别:

    public string CategoryName { get; set; }
    public ICollection<Product> Products { get; set; }

产品:

    public string ProductName { get; set; }
    [Required]
    public string ProductDescription { get; set; }
    [Required]
    public int CategoryId { get; set; }

    public Category Category { get; set; }

这是映射:

 public class ProductMapping : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.HasOne(c => c.Category).WithMany(x => x.Products).HasForeignKey(x => x.CategoryId);
    }
}

但是当我需要用CategoryName 返回产品的详细信息时,我会写这个查询:

var findProduct = await ProductEntity.Include(x => x.Category).Where(x => x.Id == key).FirstOrDefaultAsync();

但结果它显示了这个错误:

检测到不支持的可能对象循环。这可能是由于循环或对象深度大于允许的最大深度

错误是什么?我该如何解决这个问题???

【问题讨论】:

  • 我想,你必须从Product中删除Category
  • @Sajid 为什么??????
  • 我认为是问题的根源,如果你不删除它,寻找解决方案忽略它。 stackoverflow.com/questions/59199593/… 或必须是虚拟的。
  • 这与 EF 无关 - EF 在循环引用方面绝对没有问题。

标签: c# asp.net entity-framework asp.net-core entity-framework-core


【解决方案1】:

产品有一个类别,其中有产品,每个产品都有类别,其中有产品,无穷无尽。当您退回产品时,它必须被序列化,因此序列化器正在遍历这些关系,同时对每个关系进行序列化,它只是变成了一个无限循环。

这是您不应该直接将实体用于此类事情的另一个原因。使用可以显式控制深度的视图模型/DTO。例如,您可能有一个具有相关类别 DTO 的产品 DTO,但该类别 DTO 没有具有相关产品的列表。然后,序列化程序实际上可以完成,因为没有更多的关系要走。

【讨论】:

    【解决方案2】:

    使用.AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

    在注册服务时(对于 MVC、Controllers 或 AddControllerwithViews)

    @Chris Pratt 是对的,你应该避免直接使用模型而不是使用 DTO

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 1970-01-01
      • 2020-04-27
      • 2020-07-06
      • 2021-03-17
      • 2020-03-30
      • 2021-08-30
      • 2020-10-02
      • 2021-12-09
      相关资源
      最近更新 更多