简体   繁体   中英

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

I have this table 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:

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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