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

坚强是说给别人听的谎言 提交于 2019-12-24 15:27:42

问题


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

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?


回答1:


First make a DTO as follows:

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:

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;
} 



回答2:


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(). It will work.



来源:https://stackoverflow.com/questions/54468767/selecting-all-rows-based-on-a-distinct-column-in-entity-framework-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!