我想按更新到資料庫的順序回傳子孫記錄(即 itemNo)。下面的查詢按 itemNo ASC 對記錄進行排序(默認情況下)。我相信按時間戳排序,將按照更新的順序回傳記錄。
我嘗試如下添加時間戳,但沒有按預期作業。
回傳 children 和 grandChildren 的查詢:
public async Task<List<Child>> GetChild(string parentItemNo)
{
return await DbContext.Items
.Where(x => x.ItemNo== parentItemNo)
.SelectMany(x => x.Children.OrderByDescending(t => t.Timestamp).Select(c => new Child
{
ItemNo = c.ItemNo,
ItemName = c.ItemName,
Timestamp = c.Timestamp,
GrandChildItemNos = c.Children.OrderByDescending(t => t.Timestamp).Select(gc =>
new GrandChild
{
ItemNo = gc.ItemNo,
ItemName = gc.ItemName,
Timestamp = gc.Timestamp,
})
})).ToListAsync(); // may i know how iadd orderBy here
}
下面是我的 responseData 的樣子:
[
{"itemNo":"1111","itemName":"A1111", "timestamp":"AAAAAoc5I/o=", "grandChildSerialNos":[]},
{"itemNo":"2222","itemName":"B2222"," "timestamp":"AAAAAoc5I/s=", "grandChildSerialNos":[]},
{"itemNo":"3333","itemName":"C3333", "timestamp":"AAAAAoc5I/0=", "grandChildSerialNos":
[
{"itemNo":"1234","itemName":"CH1234"..},
{"itemNo":"5678","itemName":"CH5678"...}
]
},
{"itemNo":"4444","itemName":"D4444", "timestamp":"AAAAAoc5I/4=" "grandChildSerialNos":[]}
{"itemNo":"5555","itemName":"E5555", "timestamp":"AAAAAoc5I/w=" "grandChildSerialNos":[]}
]
我希望 responseData 在“3333”和“4444”之前回傳 ItemNo “5555”(因為“5555”在 3333 和 4444 之前更新)。但回應不會按該順序回傳。我希望“ItemNo”按“時間戳”而不是升序排序。
模型類如下:
public partial class Item
{
public byte[] Timestamp { get; set; }
public string itemNo { get; set; }
public string itemName { get; set; }
}
public class GrandChild
{
public string ItemNo {get;set;}
public string ItemName {get;set;}
public byte[] Timestamp { get; set; }
}
public class Child
{
public string ItemNo {get;set;}
public string ItemName {get;set;}
public byte[] Timestamp { get; set; }
public IEnumerable<GrandChild> GrandChildItemNos {get;set;}
}
uj5u.com熱心網友回復:
你有沒有嘗試過這樣的事情?
await DbContext.Items.Where(x => x.ItemNo == parentItemNo)
.SelectMany(x => x.Children)
.OrderByDescending(t => t.Timestamp).Select(c => new Child
{
ItemNo = c.ItemNo,
ItemName = c.ItemName,
Timestamp = c.Timestamp,
GrandChildItemNos = c.GrandChildItemNos.OrderByDescending(t => t.Timestamp).Select(gc =>
new GrandChild
{
ItemNo = gc.ItemNo,
ItemName = gc.ItemName,
Timestamp = gc.Timestamp,
})
}).ToListAsync();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429507.html
標籤:林克 asp.net 核心 实体框架核心 sql-order-by
