我有4個表中的DB:我可以在查詢中做GroupBy以避免poco類中的屬性嗎?
- News (NewsID(PK), NewsCategoryID(FK), NewsType (FK), NewsFormatID(FK), Caption, Description)
- NewsType (NewsTypeID (PK), Caption)
- NewsCategory(NewsCategoryID (PK), Caption)
- NewsFormat (NewsFormatID (PK), Caption)
我有2個POCO對象:
public class News
{
public int NewsID { get; set; }
public int NewsTypeID { get; set; }
public int NewsFormatID { get; set; }
public string Category{ get; set; }
public string Caption { get; set; }
public string Description { get; set; }
}
public class NewsCategory
{
public string Caption { get; set; }
public List<News> News{ get; set; }
}
我想打一個查詢返回列表。在查詢中,我想按他們的分類對新聞進行分組。我這樣做:
public static List<NewsCategory> GetNews()
{
using (var tc = new NewsDataContext())
{
var dc = tc.DataContext;
var newsQuery= (from news in dc.News
join newsCategory in dc.NewsCategories on news.NewsCategoryID equals newsCategory.NewsCategoryID
join newsType in dc.NewsTypes on news.NewsTypeID equals newsType.NewsTypeID
join newsFormat in dc.NewsFormat on news.NewsFormatID equals newsFormat.NewsFormatID
select new News
{
NewsID = news.NewsID,
NewsFormatID = newsFormat.NewsFormatID,
Caption = news.Caption,
Description = news.Description,
Category = newsCategory.Caption
});
return newsQuery.GroupBy(item => item.Category).Select(item => new NewsCategory
{
Caption = item.Key,
News= item.ToList()
}).ToList();
}
}
..這是行得通的。我的問題在於,我可以從POCO類News中刪除NewsCategory屬性,並直接在查詢中(加入後)按類別進行分組以及如何? 在此先感謝。
什麼信息? ... –
@TomPickles,對不起,已更新。 – Shimmy
我正在使用Linq2Sql。任何其他想法?我仍然希望在分組中按類別分組新聞,並且有List,其中來自NewsCategory的Caption是屬性,我希望新聞可以分組。 –
Cemsha