我有类似下面的类结构。我有一个主要类别,它可以有多个子类别,这些子类别可以进一步有子类别。我想从表中获取所有数据并将其设置为对象,然后将其转换为JSON。类别和子类别关系由ParentId
维护。 IsLast
属性告诉我此类别没有其他子类别。 IsLast
设置为true的类别将为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; }
}
我试过这样的事情,但下面的代码不起作用,请你提出一些方法。
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;
}