实体框架4.1统计相同的数据库行
本文关键字:数据库 统计 框架 实体 | 更新日期: 2023-09-27 18:19:37
我的设置
我有两个类,这里显示的是这个例子中需要的东西:
public class Photo : Entity
{
[Key]
public int Id { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public Photo()
{
Tags = new List<Tag>();
}
}
public class Tag : Entity
{
[Key]
public string Text { get; set; }
public virtual ICollection<Photo> Photos { get; set; }
public Tag()
{
Photos = new List<Photo>();
}
}
如上所示,这两个实体之间存在多对多的关系。
我首先使用EF 4.1代码。
示例:
- "photo1";具有"tag1"tag2";以及"tag3";在其标记导航属性中
- "photo2";具有"tag2"tag3";以及"tag4";在其标记导航属性中
- "photo3";具有"tag2";以及"tag4";在其标记导航属性中
所有照片中的标签总数:
- "标签1":1
- "标签2":3
- "标签3":2
- "标签4":2
- 标签总数:8
备注
我的最终目标是这个标签云,但使用MVC3:
http://www.geekzilla.co.uk/View960C74AE-D01B-428E-BCF3-E57B85D5A308.htm
第一个问题
如何(使用EF)找出使用次数最多的标签(找到"tag2"的计数)?对于最少使用的标签也是如此(在上面的例子中为"tag1"的计数)。
在上面的链接中使用这些代码行:
double.TryParse(tagData.Compute("min(count)", null).ToString(), out min);
double.TryParse(tagData.Compute("max(count)", null).ToString(), out max);
什么是等效的EF/LINQ
第二个问题
如何获得每个标签的计数或50个最常用标签的计数?
按标签计数:
from t in Context.Tags
select new
{
t.Text,
t.Photos.Count()
}
最常用的标签:
(from t in Context.Tags
let photoCount = t.Photos.Count()
orderby photoCount descending
select new
{
t.Text,
photoCount
}).FirstOrDefault()
50个最常用的标签(可能实际上没有50个):
(from t in Context.Tags
let photoCount = t.Photos.Count()
orderby photoCount descending
select new
{
t.Text,
photoCount
}).Take(50)
徒手操作,因此可能不是100%语法正确,也不是最小/最可读的方法。
编辑:添加示例:
foreach(var result in Context.Tags.Select(x => new { t.Text, t.Photos.Count() }))
{
Console.WriteLine(string.Format("Text: {0}, Count: {1}", result.Text, result.Count.ToString());
}