[英]LINQ query in Entity framework 6
I have Articles in my database. 我的数据库中有文章。 Every Article has Category property.
每个文章都有类别属性。 I want to dynamically generate menu which is based on categories and articles like that:
我想动态生成基于这样的类别和文章的菜单:
-CategoryName1
|-Article1
|-Article2
-CategoryName2
|-Article3
|-Article4
etc... 等等...
I want to create simple viewModel with this structure to dynamicaly create menu on my View. 我想用这种结构创建简单的viewModel来动态地在View上创建菜单。
There are condition also like Article.IsDeleted and Category.IsDeleted must be false. 也有条件,如Article.IsDeleted和Category.IsDeleted必须为false。 The second condition is that the generated model shouldn't contain categories which doesn't have at least 1 related article.
第二个条件是,所生成的模型不应包含没有至少1条相关文章的类别。
But I dont know how to do this, maybe by LINQ? 但是我不知道该怎么做,也许是LINQ?
I thought that this could be my viewModel (or you could propose better, more optimal?) 我以为这可能是我的viewModel(或者您可以提出更好,更优化的建议?)
public class SideMenuViewModel
{
public SideMenuViewModel()
{
this.MenuLinks = new List<CategoryLink>();
}
public IList<CategoryLink> MenuLinks { get; set; }
}
public class ArticleLink
{
public string ArticleName { get; set; }
public string ArticleUrl { get; set; }
}
public class CategoryLink
{
public CategoryLink()
{
this.ArticleLinks = new List<ArticleLink>();
}
public IList<ArticleLink> ArticleLinks { get; set; }
public string CategoryName { get; set; }
public string CategoryUrl { get; set; }
}
Action: 行动:
[ChildActionOnly]
public ActionResult SidebarMenu()
{
SideMenuViewModel model = new SideMenuViewModel();
var categories = db.Articles
.Where(x => !x.IsDeleted && !x.Category.IsDeleted && x.Category.Website.Id == WebsiteHelper.CurrentWebsiteId).Include(x => x.Category)
.Select(x => new CategoryLink() { CategoryName = x.Category.Name, CategoryUrl = x.Category.Name })
.GroupBy(x => x.CategoryName)
.Select(x => x.First());
foreach(CategoryLink item in categories)
{
}
//Get the menuItems collection from somewhere
return PartialView("_SidebarMenu", model);
}
If there are better ways than LINQ, please write them too :) 如果有比LINQ更好的方法,请也写它们:)
In this case it is easier to use Category.Articles
: 在这种情况下,使用
Category.Articles
更容易:
from c in db.Categories.Where(c => !c.IsDeleted)
let activeArticles = c.Articles.Where(a => !a.IsDeleted)
where activeArticles.Count() > 1
select new CategoryLink
{
c.CategoryName,
c.CategoryUrl,
ArticleLinks = activeArticles.Select(a1 => new ArticleLink
{
a1.ArticleName,
a1.ArticleUrl
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.