I'm trying to create an ASP.NET MVC application using repostory pattern and dependency injection as design pattern. I have 3 related models
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string TagName { get; set; }
public string TagColor { get; set; }
public string ImageUrl { get; set; }
[ForeignKey("CategoryId")]
public virtual ICollection<SubCategory> SubCategories { get; set; }
}
public class SubCategory
{
public int SubCategoryId { get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public string TagName { get; set; }
public string TagColor { get; set; }
public string ImageUrl { get; set; }
[ForeignKey("SubCategoryId")]
public virtual ICollection<SubSubCategory> SubSubCategories { get; set; }
}
public class SubSubCategory
{
public int SubSubCategoryId { get; set; }
public int SubCategoryId { get; set; }
public string Name { get; set; }
public string TagName { get; set; }
public string TagColor { get; set; }
public string ImageUrl { get; set; }
}
Now I want to define a method that will return a JSON object of all the three related models containing the data will be containing Navigation Menu(Category), SubCategories under each Category and SubSubCategory as MenuItems under each SubCategory. So How do I define repository and the method prototype ?
Also if you can suggest me any method that can do all that what I've just explained earlier using Entityframework I will be grateful to you. Thank you
foreach (Category category in context.Categories)
{
foreach (SubCategory subCategory in category.SubCategories)
{
foreach (SubSubCategory subSubCategory in subCategory.SubSubCategories)
{
}
}
}
This is what I'm doing to get all related data. If there is any good way to get all related data please let me know.
I suggest using one class instead of three different classes.
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string TagName { get; set; }
public string TagColor { get; set; }
public string ImageUrl { get; set; }
[ForeignKey("CategoryId")]
public virtual ICollection<Category> SubCategories { get; set; }
}
This way every operation on all categories can be done with a simple recursive method.
private void SomeOperation(ICollection<Category> list)
{
foreach (Category category in list)
{
//Do something
SomeOperation(category.SubCategories);
}
}
I hope it turns out to be helpful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.