【发布时间】:2016-09-05 15:20:39
【问题描述】:
我不确定如何编写 LINQ 查询。我有这些模型:
class Category
{
ICollection<Thread> Threads {get;set;}
ICollection<Category> SubCategories {get;set;}
}
class Thread
{
Category Category {get;set;}
//Some Stuff
}
所以,可能会有一些类别链接,例如 -
- 类别1
- 类别2
- 类别3
- 类别4
- 类别5
- 6 类
我想找到所有链接到 Category2 及其 SubCategories(3, 4, 5) 的线程。
我想过只取Category1表单db,并使用C#递归函数构建我需要的线程列表,但我觉得这是个坏主意。
任何想法或链接都会很棒。谢谢! 有代码,但是有主题(在线程中),我没有提到它,因为这不是问题(至少我是这么认为的)
public ActionResult ShowCategoryTopics(int id)
{
var category = db.Categories.Where(x => x.Id == id).FirstOrDefault();
var topics = GetTopics(category);
return View();
}
public List<Topic> GetTopics(Category category)
{
List<Topic> topics = new List<Topic>();
if (!category.IsDeleted && !category.IsHidden)
return null;
foreach (Thread thread in category.Threads)
{
topics.AddRange(thread.Topics.Where(x => !x.IsDeleted).ToList());
}
foreach(Category childCategory in category.SubCategories)
{
topics.AddRange(GetTopics(childCategory));
}
return topics;
}
【问题讨论】:
-
你能告诉我们你到目前为止做了什么吗?
-
你的数据库有多少个类别?
-
不多,一开始会有~10个,以后大概有100个(没想到会更多)。
标签: c# asp.net asp.net-mvc entity-framework linq