我在数据库中有 4 个表:
- 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 属性,并直接在查询中(连接后)按类别进行分组吗?如何?提前致谢。