C# 如何在GROUPBY子句结果集EF Core中包含零次出现

C# 如何在GROUPBY子句结果集EF Core中包含零次出现,c#,entity-framework-core,C#,Entity Framework Core,一个表有事件日志,我想找出where子句中给定类型的每个eventType的计数。问题是,如果我在where子句中传递事件类型,我只返回与条件匹配的事件,对于不匹配的事件,我希望返回0。例如: var data = await (from eventLogs in _context.Set<EventLog>() where (eventTypes.Contains(eventLogs.EventType))

一个表有事件日志,我想找出where子句中给定类型的每个eventType的计数。问题是,如果我在where子句中传递事件类型,我只返回与条件匹配的事件,对于不匹配的事件,我希望返回0。例如:

     var data = await (from eventLogs in _context.Set<EventLog>()
                          where (eventTypes.Contains(eventLogs.EventType))
                          group eventLogs by eventLogs.EventType
                          into log
                          select new
                          {
                              EventType = log.Key,
                              Occurrences = log.Count()
                          })
                         .ToDictionaryAsync(x => x.EventType, x => x.Occurrences);
var data=await(来自_context.Set()中的事件日志)
其中(eventTypes.Contains(eventLogs.EventType))
按eventLogs.EventType对eventLogs进行分组
进入日志
选择新的
{
EventType=log.Key,
事件数=log.Count()
})
.ToDictionaryAsync(x=>x.EventType,x=>x.events);
结果

事件类型 标题2 12 34 52 3.
我假设eventlogs没有任何typeId=71的记录。所以你可以组成一个联盟


 var data1 = await (from eventLogs in _context.Set<EventLog>()
                          where (eventTypes.Contains(eventLogs.EventType))
                          group eventLogs by eventLogs.EventType
                          into log
                          select new
                          {
                              EventType = log.Key,
                              Occurrences = log.Count()
                          })
                         .ToListAsync();

var data2 = eventTypes.Select(i=> new
{
     EventType = i,
    Occurrences = 0
}).ToList();

var data = data1.Union(data2).GroupBy(o => new {o.EventType})
                .Select(o => new 
                {
                    EventType = o.Key.EventType ,
                    Occurrences = o.Sum(q => q.Occurrences )
                }).ToDictionary(x => x.EventType, x => x.Occurrences);


var data1=await(来自_context.Set()中的事件日志)
其中(eventTypes.Contains(eventLogs.EventType))
按eventLogs.EventType对eventLogs进行分组
进入日志
选择新的
{
EventType=log.Key,
事件数=log.Count()
})
.ToListAsync();
var data2=eventTypes.Select(i=>new
{
EventType=i,
出现次数=0
}).ToList();
var data=data1.Union(data2.GroupBy(o=>new{o.EventType})
.选择(o=>new
{
EventType=o.Key.EventType,
发生次数=o.Sum(q=>q.events)
}).ToDictionary(x=>x.EventType,x=>x.events);

我假设
eventTypes
包含您感兴趣的三种事件类型?@DStanley,是的。我希望结果包括在“Where”条件下传递的所有事件类型。我希望会有某种EF core魔法来格式化SQL端的数据,但我想我们必须在从SQL Server获取数据后在内存中追加/合并不匹配的元素。谢谢你,现在可以了。