0

i have 2 table .

Product and Category .

Category :

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

Product :

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

    public Category Category { get; set; }

and this is mapping :

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

but when i need to return detail of product with CategoryName then i write this query :

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

but in result it show me this error :

A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of

whats the error ? how can i solve this problem ???

mr coder
  • 199
  • 2
  • 14

2 Answers2

1

Product has a category, which has products, each of which have categories, which have products, ad infinitum. When you return the product, it must be serialized, so the serializer is walking these relationships, serializing each of those as well, and it simply becomes an endless loop.

This is yet another reason you should not use entities directly for things like this. Use a view model/DTO where you can explicitly control the depth. For example, you might have a product DTO which has a related category DTO, but that category DTO would not have a list of related products. Then, the serializer can actually finish, because there's no more relationships to walk.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
0

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

while registering services (for MVC, Controllers or AddControllerwithViews)

@Chris Pratt is right you should avoid using models directly instead use DTO

vrs
  • 381
  • 2
  • 12