[英]LINQ Left Outer join with group by count through extension methods
我有两张桌子。 Categories
和Ads
。
每个Category
在“ Ads
表中可以有多个广告。
我想要所有类别的详细信息,包括每个类别有多少个广告。
以下是我的Linq表达式,它仅提取包含广告的类别,可能是FirstOrDefault()
我想知道如何获得结果,因为条件加上仅具有位置ID(例如:lid)为“ 7”的类别。
跟随我的表情
var x1 = context.Categories
.GroupJoin(
context.ads,
cat => cat.id,
ad => ad.catid,
(cat, ad) => new { cats = cat, ads = ad })
.SelectMany(
a => a.ads.DefaultIfEmpty(),
(a, y) => new { catss = a.cats, adss = y })
.GroupBy(w => w.adss,ww=>new { cat=ww.catss,count=ww.catss.ads.Count()})
.Where(s=>s.FirstOrDefault().cat.lid==7);
显然, Categories
和Ads
之间存在一对多的关系:每个Category
具有零个或多个Ads
,每个Ad
恰好属于一个Category
。
在适当的实体框架中,其建模方式如下:
class Category
{
public int Id {get; set;}
// every Category has zero or more Adds:
public virtual ICollection<Ad> Ads {get; set;}
...
}
class Ad
{
public int Id {get; set;}
// every Ad belongs to exactly one Category, using foreign key CategoryId:
public int CategoryId {get; set;}
public Category Category {get; set;}
...
}
如果您的类是这样建模的,则实体框架将假定类别和添加之间正确的一对多关系。 可能是某些属性的名称不同,并且使用的是Attributes和/或Fluent API,但是类的结构将相似。
完成此操作后,查询比您想象的要容易:
var result = dbContext.Categories.Select(category => new
{
Category = Category,
AdCount = Category.Adds.Count(),
};
换句话说:对于类别集合中的每个类别,创建一个具有两个属性的匿名类的新对象:
实体框架模型将理解,执行此操作需要联接和计数。
您可以尝试以下操作:
var result = context.Categories
.Where(category => category.lid == 7)
.GroupJoin(
context.ads
, category => category.id
, ad => ad.catid
, (c,a) => new
{
Category = category,
NumberOfAds = a.DefaultIfEmpty().Count(x => x!=null)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.