代码之家  ›  专栏  ›  技术社区  ›  Zdenek G

在嵌套集合中将IQueryable转换为IList

  •  1
  • Zdenek G  · 技术社区  · 11 年前

    我有来自实体框架的以下实体: Parent、Child、GrandChild和等效实体ParentModel和ChildModel。

    简化:

    class ParentModel
    {
        public IList<ChildModel> Children { get; set; }
    }
    
    class ChildModel
    {
        public string GrandChild { get; set; }
    }
    

    在父级扩展上,我有方法“ToModel”

    public static IEnumerable<ProductCategoryModel> ToModel(
        this IQueryable<ProductCategory> query)
    {
        IList<ParentModel> model = 
           query.Select(p => new ParentModel { 
                                Childs = p.Childs.Select(ch => new ChildModel { 
                                                     Grandchild = ch.Grandchild.Code
                                                  }).ToList() 
                        }).ToList();
    
        return model;
    }
    

    问题是它不起作用。 我知道为什么嵌套的ToList()方法不能在DB端运行。

    有什么简单的解决方案可以写正确的等效代码吗?我在foreach中看到了一些解决方案,但在我看来,这并不好。

    1 回复  |  直到 11 年前
        1
  •  0
  •   Daniel Hilgarth Richard    11 年前

    您将分两个步骤进行工作:

    1. 获取所需数据
    2. 把它做成你想要的形状
    public static IEnumerable<ProductCategoryModel> ToModel(
        this IQueryable<ProductCategory> query)
    {
        return query.Select(p => new
                            {
                              Children = p.Childs
                                          .Select(ch => new ChildModel()
                                                  { 
                                                    Grandchild = ch.Grandchild.Code
                                                  })
                            })
                    .AsEnumerable()
                    .Select(x => new ParentModel { Children = x.Children.ToList() })
                    .ToList();
    }