简体   繁体   English

根据Entity Framework Core中的不同列选择所有行

[英]Selecting all rows based on a distinct column in Entity Framework Core

I have a table with some data which I want to select rows with unique dates using the .NET core entity framework. 我有一个包含一些数据的表,我想使用.NET核心实体框架选择具有唯一日期的行。 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 我正在尝试应用上述代码,但出现此错误

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>'. 无法将类型'System.Collections.Generic.List <System.Linq.IGrouping <System.DateTime,Test.API.Models.Records >>'隐式转换为'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? 还有什么其他方法可以实现我的期望,或者我在代码中缺少某些内容?

First make a DTO as follows: 首先按照以下步骤进行DTO

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

To select rows with unique dates, you have to use .GroupBy and write your GetUniqueRecordsByDate method as follows: 要选择具有唯一日期的行,您必须使用.GroupBy并按如下所示编写GetUniqueRecordsByDate方法:

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;
} 
var rowsToReturn = await _context.Records
            .Where(b => b.SId == bId)
            .Select(d => d.Date)
            .Distinct()
            .OrderBy(d => d)
            .AsEnumerable()
            .ToListAsync();
return rowsToReturn;

Use AsEnumerable() before ToListAsync(). 在ToListAsync()之前使用AsEnumerable()。 It will work. 它会工作。

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

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