我在db中有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; }
}
我想进行查询以返回List。在查询中,我想按类别对新闻进行分组。我是这样做的:
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类新闻中删除NewsCategory属性,并在查询中直接按类别进行分组(在连接之后)以及如何? 提前致谢。
答案 0 :(得分:1)
您可以在新闻POCO中添加一个NewsCategory属性,并使其延迟/显式加载。
查看this帖子了解详情。
答案 1 :(得分:1)
此代码演示了如何在执行查询后加载行/列数据并对其进行整形。它不会“在数据库中分组”,但它确实允许删除News.Category属性。
var query= (
from news in dc.News
from newsCategory in news.NewsCategories
let newsFormat = news.NewsFormat
select new //anon type
{
NewsID = news.NewsID,
NewsFormatID = newsFormat.NewsFormatID,
Caption = news.Caption,
Description = news.Description,
Category = newsCategory.Caption
});
//Load anon rows
var rows = query.ToList();
//shape the anon rows into our POCSO's.
List<NewsCategory> result = rows
.GroupBy(item => item.Category)
.Select(g => new NewsCategory()
{
Caption = g.Key,
News = g.Select(row => new News()
{
NewsID = row.NewsID,
NewsFormatID = row.NewsFormatID,
Caption = row.Caption,
Description = row.Description
}
})
.ToList();
return result;
您有理由不想“在数据库中分组”。 group by的数据库行为是返回密钥和聚合。您需要键和组元素。为了获取每个组的group元素,linqtosql将使用每个组的键重新查询数据库。这会导致许多往返(称为n + 1问题,其中n是组的数量,+1是获取密钥的查询)。
Enumerable.GroupBy
方法返回组键和元素 - 这正是您想要的。