C# 带有“Group By”和/或“Order by”的实体框架
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1562807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity framework with "Group By" and/or "Order by"
提问by Simon Dugré
Say we've got a project that allows user to download things. On the main page, I want to show the Most downloaded files ordered by the number of download! All that using EF.
假设我们有一个允许用户下载东西的项目。在主页面上,我想显示按下载次数排序的下载次数最多的文件!所有这些都使用 EF。
How can i do this !! I've tried many things with Group By (Its a nightmare when you've got a lot of informations in an object). And i still dunno how to do this...
我怎样才能做到这一点 !!我已经用 Group By 尝试了很多东西(当你在一个对象中有很多信息时,这是一场噩梦)。我仍然不知道如何做到这一点......
var query = from details in m_context.TransactionDetails
where details.Chanson != null
group details by details.Items into AnItem
orderby AnItem.Count()
select new Item() {
IdItem = Chansons.Key.IdItem,
ItemState= Chansons.Key.ItemState,
[...This object got something like 20 including links to other objects ... ]
};
Anyone have an idea?
有人有想法吗?
Thanks :o)
谢谢:o)
Oh and sorry for my english, I'm giving my best but im from Quebec (Usualy talk french).
哦,对不起我的英语,我正在尽我所能,但我来自魁北克(通常说法语)。
采纳答案by Craig Stuntz
Salut!
致敬!
I'm going to guess at your data model a little, here, but I don't think you need to group:
我将在这里稍微猜测一下您的数据模型,但我认为您不需要分组:
var query = from details in m_context.TransactionDetails
where details.Chanson != null
orderby details.Items.Count() descending
select new Item
{
IdItem = details.Chanson.IdItem,
ItemState= details.Chanson.ItemState,
// ...
};
Bonne chance!
博纳机会!
Update:For albums:
更新:对于专辑:
var query = from details in m_context.TransactionDetails
where details.DisqueCompact != null
orderby details.Items.Count() descending
select new Item
{
IdItem = details.DisqueCompact.IdItem,
ItemState= details.DisqueCompact.QuelqueChose...
// ...
};
You probably need two queries given your data model.
给定您的数据模型,您可能需要两个查询。
回答by Tariqul Islam
This is an example of how you should do it:
这是你应该如何做的一个例子:
//this is a entity framework objects
CTSPEntities CEntity = new CTSPEntities();
//and this is your example query
var query = (from details in CEntity.Purchase_Product_Details
group details by new { details.Product_Details.Product_Code, details.Product_Details.Product_Name} into Prod
select new
{
PID = Prod.Key.Product_Code,
PName = Prod.Key.Product_Name,
Amount = Prod.Sum(c => c.Lot_Amount),
count= Prod.Count()
}).OrderBy(x => x.Amount);
foreach (var item in query)
{
Console.WriteLine("{0},{1},{2},{3}",item.PID,item.PName,item.Amount,item.count);
}
Console.ReadLine();