有谁能告诉我如何在Entity Framework 4.0中编写以下查询? “博客”和“类别”是我的实体。该查询基本上返回了类别列表和该类别中的博客数量。
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
提前致谢。
答案 0 :(得分: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] };
在Entity SQL查询中,您应该将MyEntities
替换为您的上下文的名称。
var nrBlogsPerYear = from b in oc.Blogs
group b by b.CreatedDate.Year into g
select new { Year = g.Key, NrBlogs = g.Count() };
答案 1 :(得分: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()
};
答案 2 :(得分: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();