根据Entity Framework Core中的不同列选择所有行 [英] Selecting all rows based on a distinct column in Entity Framework Core

查看:94
本文介绍了根据Entity Framework Core中的不同列选择所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些数据的表,我想使用.NET核心实体框架选择具有唯一日期的行.我想将结果作为唯一行的列表返回.这是代码.

I have a table with some data which I want to select rows with unique dates using the .NET core entity framework. I want to return the results as a list of the unique rows. Here is the code.

public async Task<IEnumerable<Records>> GetUniqueRecordsByDate(int bId)
{
     var rowsToReturn = await _context.Records
                .Where(b => b.SId == bId)
                .Select(d => d.Date)
                .Distinct()
                .OrderBy(d => d)
                .ToListAsync();
     return rowsToReturn;
} 

我正在尝试应用上面的代码,但出现此错误

I'm trying to apply the above code but I get this error

无法隐式转换类型'System.Collections.Generic.List< System.Linq.IGrouping< System.DateTime,Test.API.Models.Records >>'到'System.Collections.Generic.IEnumerable< Test.API.Models.Record>.存在显式转换(您是否缺少演员表?)

Cannot implicitly convert type 'System.Collections.Generic.List< System.Linq.IGrouping< System.DateTime, Test.API.Models.Records>>'to 'System.Collections.Generic.IEnumerable< Test.API.Models.Record>'. An explicit conversion exists (are you missing a cast?)

还有什么其他方法可以实现我的期望,或者我在代码中缺少某些内容?

Is there any other way that I can implement to get my expectations or I'm I missing something in my code?

推荐答案

首先如下创建DTO:

public class RecordsByDateDTO
{
    public DateTime Date {get; set;}
    public List<Record> Records {get; set;}
}

要选择具有唯一日期的行,必须使用.GroupBy并编写如下的GetUniqueRecordsByDate方法:

To select rows with unique dates, you have to use .GroupBy and write your GetUniqueRecordsByDate method as follows:

public async Task<List<RecordsByDateDTO>> GetUniqueRecordsByDate(int bId)
{
     var recordsByDate = await _context.Records.Where(r => r.SId == bId).GroupBy(r => r.Date)
                              .Select(group => new RecordsByDateDTO
                              {
                                   Date =  group.Key,
                                   Records = group.ToList()
                              }).OrderBy(r => r. Date).ToListAsync();

    return recordsByDate;
} 

这篇关于根据Entity Framework Core中的不同列选择所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆