Getting overflow stack error when adding self-referencing entity in entity framework

45 Views Asked by At

I have a class named category in my project. I am trying to make subcategories of categories. The category class is self-referencing. My category class.

public class Category : IEntity
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get =>  this.Id; set => this.Id = value; }
        public int? IsSubCategoryOf { get; set; }
        public string CategoryName { get; set; }
        public DateTime AddedAt { get; set; }
        public bool IsActive { get; set; }

        public virtual Category ParentCategory { get; set; }
        public virtual IList<Category> SubCategory { get; set; }
        public List<Ad> Ads { get; set; }
    }

My context class.

modelBuilder.Entity<Category>(entity =>
            {
                entity.HasOne<Category>(c => c.ParentCategory).WithMany(c => c.SubCategory).HasForeignKey(c => c.IsSubCategoryOf);
            });

I am getting an overflow stack error while inserting data into the database. My Repository class.

public Category Add(Category entity)
        {
            _context.Categories.Add(entity);
            _context.SaveChanges();

            return entity;
        }

How can i solve this problem?

controller class.

try
            {
                Category categoryDb = new Category();
                if(category.IsSubCategoryOf == -1)
                {
                    categoryDb.CategoryName = category.CategoryName;
                    categoryDb.AddedAt = category.AddedAt;
                    categoryDb.IsActive = category.IsActive;
                    _context.Categories.Add(categoryDb);
                    _context.SaveChanges();
                }
                else
                {
                    Category parentCategoryDb = _context.Categories.Include(c => c.SubCategory).Where(c => c.Id == category.IsSubCategoryOf).FirstOrDefault();
                    categoryDb.CategoryName = category.CategoryName;
                    parentCategoryDb.SubCategory.Add(categoryDb);
                    _context.SaveChanges();
                }
                return Ok(categoryDb);
            }
            catch (Exception)
            {
                return BadRequest();
            }
0

There are 0 best solutions below