根据实体框架核心中的不同列选择所有行

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

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

我正在尝试应用上述代码,但我收到此错误

无法将类型“System.Collections.Generic.List< System.Linq.IGrouping< System.DateTime, Test.API.Models.Records>>'转换为'System.Collections.Generic.IEnumerable<Test.API.Models.Record>'。存在显式转换(您是否缺少强制转换?

有没有其他方法可以实现以获得我的期望,或者我在代码中遗漏了一些东西?


呼啦一阵风
浏览 73回答 2
2回答

蝴蝶不菲

首先做一个如下:DTOpublic class RecordsByDateDTO{&nbsp; &nbsp; public DateTime Date {get; set;}&nbsp; &nbsp; public List<Record> Records {get; set;}}若要选择具有唯一日期的行,必须按如下方式使用和编写方法:.GroupByGetUniqueRecordsByDatepublic async Task<List<RecordsByDateDTO>> GetUniqueRecordsByDate(int bId){&nbsp; &nbsp; &nbsp;var recordsByDate = await _context.Records.Where(r => r.SId == bId).GroupBy(r => r.Date)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(group => new RecordsByDateDTO&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Date =&nbsp; group.Key,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Records = group.ToList()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }).OrderBy(r => r. Date).ToListAsync();&nbsp; &nbsp; return recordsByDate;}&nbsp;

慕斯709654

var&nbsp;rowsToReturn&nbsp;=&nbsp;await&nbsp;_context.Records &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Where(b&nbsp;=>&nbsp;b.SId&nbsp;==&nbsp;bId) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Select(d&nbsp;=>&nbsp;d.Date) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.Distinct() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.OrderBy(d&nbsp;=>&nbsp;d) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.AsEnumerable() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.ToListAsync();return&nbsp;rowsToReturn;在 ToListAsync() 之前使用 AsEnumerable()。它会起作用。
打开App,查看更多内容
随时随地看视频慕课网APP