简体   繁体   English

实体框架 - 按一列分组并选择多列

[英]Entity Framework - grouping by one column and selecting multiple columns

I have this method for my API where I'm trying to filter out a user ( userId ) and group by EventId .我的 API 有这个方法,我试图过滤掉用户( userId )并按EventId分组。 Then I want to select three columns from the table: name , eventId and UserId .然后我想从表中选择三列: nameeventIdUserId

This is my code but it's not working:这是我的代码,但它不起作用:

[HttpGet("[action]/{userId}")]
public IActionResult EventsMatchFiltered(int userId)
{
    var events = _dbContext.Events.Where(event1 => event1.UserId != userId)
       .GroupBy(g => new {g.EventId })
       .SelectMany(g => g.Select(h => new 
       {
           Name = h.Name, 
           h.EventId, 
           h.UserId 
       }));
    return Ok(events);
}

Firstly, events would be an IQueryable rather than a materialized collection.首先,事件将是一个IQueryable而不是物化集合。 Second, it would be an anonymous type rather than a proper DTO/ViewModel serializable class.其次,它将是一个匿名类型,而不是一个适当的 DTO/ViewModel 可序列化类。 Thirdly, you are grouping by an EventId, but then not "selecting" anything based on that grouping.第三,您按 EventId 进行分组,但不根据该分组“选择”任何内容。 EventId sounds like the Primary Key of the Event you are supposedly grouping.. Are you sure you don't actually mean to Group by User?? EventId 听起来像是您应该分组的事件的主键.. 您确定您实际上不是要按用户分组吗?

Normally for something like a Grouped result you would have a view model something like:通常对于像 Grouped 结果这样的东西,你会有一个像这样的视图模型:

[Serializable]
public class UserEventSummaryViewModel
{
    public int UserId { get; set; }
    public ICollection<EventSummaryViewModel> Events { get; set; } = new List<EventSummaryViewModel>();
}

[Serializable]
public class EventSummaryViewModel
{
    public int EventId { get; set; }
    public string Name { get; set; }
}

then to query and fill:然后查询并填写:

var otherUserEvents = _dbContext.Events
   .Where(e => e.UserId != userId)
   .GroupBy(g => g.UserId )
   .Select(g => new UserEventSummaryViewModel
   { 
       UserId == g.Key,
       Events = g.Select(e => new EventSummaryViewModel
       {
           EventId = e.EventId,
           Name = e.Name
       }).ToList()
   }).ToList();

This would provide a structure of events grouped by each of the other Users.这将提供按每个其他用户分组的事件结构。 If you want UserId and UserName then add the UserName property to the UserEventSummary view model and in the GroupBy clause:如果您需要 UserId 和 UserName,则将 UserName 属性添加到 UserEventSummary 视图模型和 GroupBy 子句中:

.GroupBy(g => new { g.UserId, g.Name } )

and populate these in the viewmodel with:并在视图模型中填充这些:

UserId == g.Key.UserId,
UserName = g.Key.Name,

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

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