0

I have a class structure like below. I have a main category and it can have multiple subcategories and these subcategories can further have subcategories. I want to get all the data from the table and set it to an object and then convert it to a JSON. Category and subcategory relationship is maintained by ParentId. IsLast property tell me that this category has no further subcategories. A category with IsLast set to true will have List<Recipe>.

public class Category
{
    public int id { get; set; }
    public string categoryName { get; set; }
    public string categoryDesc { get; set; }
    public bool isLast { get; set; }
    public int parentId { get; set; }
    public int level { get; set; }
    public List<Category> Category { get; set; }
    public List<Recipe> Recipe { get; set; }
}


public class Recipe
{
    public int id { get; set; }
    public string RecipeName { get; set; }
    public string RecipeDesc { get; set; }

}

public class CategoryRecipe
{
    public int RecipeId { get; set; }
    public int CategoryId { get; set; }
}

I tried something like this, but the below code does not work, Could you please suggest some approach.

public CategoryDto GetAllCategories(int parentId, int level)
{
    CategoryDto category = new CategoryDto();
    Category mainCategory = null;

    if (parentId == 0)
    {
        mainCategory = _categoryRepository.GetAll().Where(x => x.Level == 0).FirstOrDefault();
    }
    else
    {
        mainCategory = _categoryRepository.GetAll().Where(x => x.ParentId == parentId).FirstOrDefault();
    }

    if (mainCategory == null)
    {
        return null;
    }

    if (mainCategory.IsLast == true)
    {
        category.RecipeTemplate = ObjectMapper.Map<List<CategoryRecipe>>(_categoryRecipeTypesRepository.
            GetAll().Where(x => x.CategoryId == mainCategory.Id).ToList());
        return category;
    }

    var subcategories = _categoryRepository.GetAll().Where(x => x.ParentId == mainCategory.Id).ToList();


    var tempList = new List<Category>();
    foreach (Category cat in subcategories)
    {
        var subcategory = GetAllCategories(cat.Id, level + 1);

        if (subcategory != null)
        {
            tempList.Add(ObjectMapper.Map<Category>(subcategory)); //AutoMap
        }
    } 

    category.Category = tempList;

    return category;
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197

0 Answers0