0
我試圖從列表中列出文章列出了每篇文章列出的類別列表。說文章「A」有3個類別「1」,「2」,「3」,我有超過一個類別的多個文章。我想獲取ArticleViewModel內的CategoryViewModel的列表。因爲它是IEnumerableList,所以當我使用FirstOrDefault()時,我在每篇文章下獲得相同的類別名稱,但是我獲得了正確的文章數量。如何在文章(列表)中獲得類別名稱(列表)。使用LINQ到實體的內部查詢(子查詢),返回列表中的IEnumerable列表
ArticleViewModel類
public class ArticleViewModel { public int ArticleID { get; set; } public int AuthorID { get; set; } public string AuthorName { get; set; } public string Username { get; set; } public string Slug { get; set; } public string Title { get; set; } public string ArticleContent { get; set; } public DateTime PostDate { get; set; } public Nullable UpdatedDate { get; set; } public int ArticleCategoryID { get; set; } public int CategoryID { get; set; } public IEnumerable CategoryNames { get; set; } public int TagID { get; set; } public string TagName { get; set; } }
CategoryViewModelClass
public class CategoryViewModel { public int CategoryID { get; set; } public string CategoryName { get; set; } }
ArticleCategory
public partial class ArticleCategory { public int ArticleCategoryID { get; set; } public int ArticleID { get; set; } public int CategoryID { get; set; } public virtual Article Article { get; set; } public virtual Category Category { get; set; }
QUERY
result = (from articles in db.Articles join articlecategories in db.ArticleCategories on articles.ArticleID equals articlecategories.ArticleID join cat in db.Categories on articlecategories.CategoryID equals cat.CategoryID join auth in db.Authors on articles.AuthorID equals auth.AuthorID select new ArticleViewModel { AuthorName = auth.AuthorName, Username = auth.UserName, CategoryNames = (from a in db.Articles //from ca in db.ArticleCategories //from c in db.Categories group c by c.CategoryName into group1 join ca in db.ArticleCategories on articlecategories.ArticleID equals ca.ArticleID join c in db.Categories on cat.CategoryID equals c.CategoryID into group1 select new CategoryViewModel { CategoryName = (from group2 in group1 select group2.CategoryName).FirstOrDefault() // CategoryID = (from group2 in group1 select group2.CategoryID).FirstOrDefault() }), Title = articles.Title, Slug = articles.Slug, ArticleContent = articles.ArticleContent, PostDate = articles.PostDate }).GroupBy(a => a.Title).Select(a => a.FirstOrDefault()).OrderByDescending(article => article.PostDate).ToList().ToPagedList(pageIndex, pageSize);