2010-08-14 106 views
2

任何人都可以告诉我如何在Entity Framework 4.0中编写以下查询吗? “博客”和“类别”是我的实体。查询基本上返回了类别列表和该类别中的博客数量。Entity Framework 4 INNER JOIN帮助

SELECT b.CategoryId, c.Value, Count(b.Id) AS [Count] FROM dbo.Blogs b 
INNER JOIN dbo.Categories c ON b.CategoryId = c.Id 
GROUP BY b.CategoryId, c.Value 

在此先感谢。

回答

3

以下应该工作(LinqToEntities):

var categories = from c in oc.Categories 
       select new 
       { 
        CategoryId = c.Id, 
        c.Value, 
        Count = c.Blogs.Count() 
       } 

这会给你的类别ID的列表和值的对于每个类别ID,您可以获得该类别中的博客数量。

编辑:给你的评论中的问题给出一个答案:这是不可能在LinqToEntities中,但你可以在实体SQL中做到这一点。

var results = new ObjectQuery<DbDataRecord>(
    @"SELECT y, COUNT(y) 
     FROM MyEntities.Blogs AS b 
     GROUP BY YEAR(b.CreatedDate) AS y", entities).ToList(); 
var nrBlogsPerYear = from r in results 
        select new { Year = r[0], NrBlogs = r[1] }; 

在实体SQL查询中,应该用您的上下文的名称替换MyEntities

编辑:正如我刚才通过克雷格评论发现,在今年is possible在L2E分组,所以你可以写你的查询是这样的:

var nrBlogsPerYear = from b in oc.Blogs 
         group b by b.CreatedDate.Year into g 
         select new { Year = g.Key, NrBlogs = g.Count() }; 
+0

谢谢!它工作完美。我不知道我们可以在没有定义具有这些属性的类的情况下“选择新的”。 – tempid 2010-08-14 19:44:42

+0

如果你不介意的话,还有一个简单的问题。我如何编写一个L2E查询来返回Year和当年的博客数量。 Blog.CreatedDate有最新信息,我寻找类似 年计数 ----------- 2010年第12 2009年45 等。这样我就可以像UI显示2010 (12),2009(45)..谢谢! – tempid 2010-08-14 19:56:02

+1

您也可以在L2E中进行年份分组。 [L2E支持Year属性](http://msdn.microsoft.com/en-us/library/bb738681.aspx) – 2010-08-16 13:55:45

2

如果你在你的实体导航属性,你可以这样做:

var cats = from c in db.Categories 
      let count = c.Blogs.Count() 
      where count > 0 
      select new 
      { 
       CategoryId = c.Id, 
       Value = c.Value, 
       Count = count 
      }; 

如果你喜欢使用显式连接,你可以做这样的:

var cats = from c in db.Categories 
      join b in db.Blogs on c.Id equals b.CategoryId into g 
      select new 
      { 
       CategoryId = c.Id, 
       Value = c.Value, 
       Count = g.Count() 
      }; 
+0

感谢您的效应初探。 – tempid 2010-08-14 19:46:04

+0

这太好了。但我的情况我不能罚款'b.CategoryId'。如果我使用'b.CategoryID',则显示该属性不存在的错误。我可以通过提供'b.Category.Id'来避免编译时间问题。但在这种情况下,结果与Inner Join不等效(http://msdn.microsoft.com/zh-cn/library/bb896266.aspx)。我的问题是http://stackoverflow.com/questions/11506333/foregin-keys-are-not-mapped-in-the-entity-framework-version-4-0 – kbvishnu 2012-07-17 06:10:40

1
var query = from p in B.Products 
      join c in B.Categories on p.CategoryID equals c.CategoryID 
      orderby c.CategoryName,p.ProductName 
      select new 
      { 
       c.CategoryName , 
       p.ProductName, 
       p.ReorderLevel 
      }; 

GridView1.DataSource = query.ToList(); 
GridView1.DataBind();