下面的查詢在字典陣列中回傳子孫的 ItemNo,以便保持這種關系。
public async Task<List<KeyValuePair<string, IEnumerable<string>>>> GetChild(string parentItemNo)
{
var childDetails = await DbContext.Items
.Where(x => x.ItemNo== parentItemNo)
.SelectMany(x => x.Children.Select(c => new
{
c.ItemNo, // I can select c.ItemName as well
// how do I select ItemName below, tried Select(gc => new { gc.ItemNo, gc.ItemName})
GrandChildItemNos = c.Children.Select(gc => gc.ItemNo)
})).ToListAsync();
var dictionary = childDetails.ToDictionary(d => d.ItemNo, d => d.GrandChildItemNos).ToList(); // how do i set ItemName here
return dictionary;
}
查詢回傳 children(key) 和 grandchild(value),如下所示
[{"Key":"A","Value":["AQ11", AH45]},{"Key":"C","Value":["CN22", "CL33", "CG24"]}]
我如何為每個子孫回傳“ItemName”。
uj5u.com熱心網友回復:
你應該寫:
public async Task<List<Child>> GetChild(string parentItemNo)
{
return await DbContext.Items
.Where(x => x.ItemNo== parentItemNo)
.SelectMany(x => x.Children.Select(c => new Child
{
ItemNo = c.ItemNo,
ItemName = c.ItemName,
GrandChildItemNos = c.Children.Select(gc =>
new GrandChild
{
ItemNo = gc.ItemNo,
ItemName = gc.ItemName
})
})).ToListAsync();
}
使用這個類
public class GrandChild
{
public string ItemNo {get;set;}
public strng ItemName {get;set;}
}
public class Child
{
public string ItemNo {get;set;}
public string ItemName {get;set;}
public IEnumerable<GrandChild> GrandChildItemNos {get;set;}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/428907.html
標籤:sql 林克 实体框架核心 asp.net-core-webapi
