[英]LINQ query orderBy a subquery
如何使用包含表的 LINQ 查詢按日期排序
public async Task<IList<TaskSchedule>> GetTask(int id)
{
var taskSchedule = await _context.TaskSchedules
.Where(u => u.Id == id)
.Include(ts => ts.Notes.OrderBy(i => i.DateCreated)) //this is what needs to be in ascneding order of date
.Include(ts => ts.Attachments)
.Include(c => c.customer)
.ToListAsync();
return taskSchedule;
}
下面的代碼有效,但是,它沒有按日期升序整理筆記
public async Task<IList<TaskSchedule>> GetTask(int id)
{
var taskSchedule = await _context.TaskSchedules
.Where(u => u.Id == id)
.Include(ts => ts.Notes)
.Include(ts => ts.Attachments)
.Include(c => c.customer)
.ToListAsync();
return taskSchedule;
}
我收到的錯誤消息是 500(內部服務器錯誤)
System.ArgumentException:類型“System.Linq.IOrderedQueryable
1[Schedular.API.Models.Note]' cannot be used for return type 'System.Linq.IOrderedEnumerable
表達式1[Schedular.API.Models.Note]' cannot be used for return type 'System.Linq.IOrderedEnumerable
1[Schedular.API.Models.Note]”
這是我使用工作代碼時返回的 API 數據。 筆記需要按照創建日期的順序排列。 目前,情況正好相反。
[
{
"id": 102,
"title": "this should display",
"start": null,
"end": null,
"isClosed": false,
"highPriority": false,
"hasTimeLimit": false,
"customer": null,
"customerId": null,
"notes": [
{
"id": 70,
"notesInfo": "add some notes first",
"dateCreated": "2020-11-17T12:20:00",
"user": null,
"userId": 1,
"taskScheduleId": 102
},
{
"id": 72,
"notesInfo": "add some notes second",
"dateCreated": "2020-11-18T16:35:00",
"user": null,
"userId": 1,
"taskScheduleId": 102
},
{
"id": 73,
"notesInfo": "add some notes third",
"dateCreated": "2020-11-19T18:35:00",
"user": null,
"userId": 1,
"taskScheduleId": 102
}
],
"attachments": [],
"userCurrentAssignedId": 1,
"userCurrentAssigned": null,
"userLastEditId": 1,
"userLastEdit": null,
"userLastEditDate": "2020-11-19T15:37:00",
"taskCreatedDate": "2020-11-19T15:37:00"
}
]
總結一下這個問題和評論。
此查詢最初僅受EF Core 5 及更高版本支持。 Include
不是子查詢,它是 EF Core 加載相關實體的指令,EF Core 5 中引入了此功能的演變。
無論如何,通常不需要進行此類查詢,因為它們與 DTO 映射相關。 因此,只需手動進行此類映射,此查詢也應適用於 EF Core 3.x。
var taskSchedule =
from ts in await _context.TaskSchedules
where ts.Id == id
select new TaskScheduleDTO
{
Notes = ts.Notes.OrderBy(n => n.DateCreated).ToList(),
Attachments = ts.Attachments.ToList(),
Cutomser = ts.Customer
}
在Include
使用OrderBy
是無效的,更改如下:
var taskSchedule = await _context.TaskSchedules
.Where(u => u.Id == id)
.Include(ts => ts.Notes)
.Include(ts => ts.Attachments)
.Include(c => c.customer)
.ToListAsync();
taskSchedule.ForEach(t => t.Notes = t.Notes.OrderBy(n => n.DateCreated).ToList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.