简体   繁体   English

如何使用LINQ和Entity Framework对总计进行分组?

[英]How can I do a group by with totals using LINQ and Entity Framework?

I have this table DDL: 我有此表DDL:

CREATE TABLE [dbo].[Audit] 
(
    [AuditId] INT          IDENTITY (1, 1) NOT NULL,
    [Entity]  INT          NOT NULL,
    [UserId]  INT          NOT NULL,
    [Note]    VARCHAR(200) NULL,
    [Date]    DATETIME     NOT NULL,
    [Action]  INT          NOT NULL,

    CONSTRAINT [PK_Audit] 
        PRIMARY KEY CLUSTERED ([AuditId] ASC)
);

What I would like to do is to get a report that shows something like this: 我想做的是获取一份显示如下内容的报告:

UserId  Action  Count
---------------------    
user1   Insert  25
user1   Update  30
User1   Delete  45

I have been using Entity Framework for my queries like this: 我一直在使用Entity Framework这样的查询:

var result = db.Audits
              .Where(a => a.UserId == userId)
              .OrderByDescending(a => a.AuditId)
              .ToList();
return Ok(result);

Can someone tell me: is it possible to get the kind of report that I need with EF or do I need to resort to a SQL statement and then somehow get the output of that? 有人可以告诉我:是否可以使用EF获得我需要的那种报告,或者我需要诉诸SQL语句然后以某种方式获取它的输出?

You can use this 你可以用这个

Audits.Where(a => a.UserId == userId)
            .GroupBy(a => a.Action)
            .Select(a => new { UserId = userId, Action = a.Key, Count = a.Count() })
            .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM