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?