【问题标题】:How do I make my query return one another property inside dictionary如何让我的查询返回字典中的另一个属性
【发布时间】:2022-02-07 23:16:32
【问题描述】:

以下查询在字典数组中返回子孙的 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”。

【问题讨论】:

    标签: sql linq entity-framework-core asp.net-core-webapi


    【解决方案1】:

    你应该写:

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

    【讨论】:

    • 谢谢。我已经做到了。但是我如何在最后一行返回(ItemName)。
    • 字典中的值现在应该包含 ItemNo 和 ItemName。所以我认为您不需要任何其他更改。
    • 变量字典的“List>>”与我的返回类型“List>>”不匹配。由于我现在发送两个字符串(itemNo,ItemName)作为值,我可以知道什么是合适的返回类型。
    • 好的,更新我的答案来解决你的问题。
    • 上述对模型的更改是否会影响现有表?由于它也被另一个应用程序使用,如果它会影响当前的表结构,则不能对模型进行更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多