-1

i have models

public class ProductModel
{
    public int ProductId { get; set; }
    
    public int BrandId { get; set; }
    [ForeignKey("BrandId")]
    public virtual BrandModel Brand { get; set; }
}

and

public class BrandModel
{
    public int BrandId { get; set; }
    public string BrandName { get; set; }
   
    public ProductModel Product { get; set; }
}

my context

public class ApplicationContext : DbContext
{
    public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
    {
    }
    public DbSet<BrandModel> Brand { get; set; }
    public DbSet<ProductModel> Product { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<BrandModel>().ToTable("Brand").HasKey(k=>k.BrandId);
        modelBuilder.Entity<BrandModel>().Property(p => p.BrandId).IsRequired().HasMaxLength(30);

        modelBuilder.Entity<ProductModel>().ToTable("Product").HasKey(k => k.ProductId);

        modelBuilder.Entity<ProductModel>()
            .HasOne<BrandModel>(p => p.Brand)
            .WithOne(b => b.Product)
            .HasForeignKey<ProductModel>(pr => pr.BrandId);
    }
}

i want take products with Brand. 1 product have 1 brand then i make simple method with include

var result = await _context.Product.Include(x => x.Brand).ToListAsync();

i see data from the database, but there is a loop

System.Text.Json.JsonException: 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 32.

it finds a product with a brand, but the brand has a product model that has a brand model ...

how can you remove this loop and get a product with a brand?

mj1313
  • 7,930
  • 2
  • 12
  • 32
cickness
  • 737
  • 2
  • 6
  • 13
  • Does [this](https://entityframeworkcore.com/knowledge-base/59199593/-net-core-3-0-possible-object-cycle-was-detected-which-is-not-supported) answer your question? – Connell.O'Donnell Jan 12 '21 at 12:29
  • Also if you don't want to switch to Json.Net - .NET 5 has now support for [reference loop handling](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.referencehandler.preserve?view=net-5.0) – Guru Stron Jan 12 '21 at 12:36

1 Answers1

0

This is caused by object nesting or preloading of ef query (associated loading), just like the "object loop" explained, the hierarchy is too deep to parse.

Add nuget package

Microsoft.AspNetCore.Mvc.NewtonsoftJson

Add the configuration in startup

services.AddControllers().AddNewtonsoftJson(option =>
            //Ignore circular references
            option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        );
Karney.
  • 4,803
  • 2
  • 7
  • 11