[英]Where to add method prototype in case of accessing data from 3 related models in repository pattern
I'm trying to create an ASP.NET MVC application using repostory pattern and dependency injection as design pattern. 我正在尝试使用重新记录模式和依赖项注入作为设计模式来创建ASP.NET MVC应用程序。 I have 3 related models
我有3个相关模型
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. 现在,我想定义一个方法,该方法将返回包含数据的所有三个相关模型的JSON对象,该模型将包含导航菜单(类别),每个类别下的SubCategories和每个SubCategory下的SubSubCategory作为MenuItems。 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. 另外,如果您可以向我建议使用Entityframework可以完成我刚才解释的所有功能的任何方法,我将不胜感激。 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. 希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.