【问题标题】:Convert IQueryable to IList in nested collection在嵌套集合中将 IQueryable 转换为 IList
【发布时间】:2013-10-30 01:27:15
【问题描述】:

我有来自实体框架的这个实体: 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 中看到了一些解决方案,但在我看来,它不会很好。

【问题讨论】:

  • “它不起作用”并没有告诉我们发生了什么。你有例外吗?它会给出空的结果吗?还有什么?

标签: c# entity-framework iqueryable ilist


【解决方案1】:

您将分两步工作:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 2021-08-27
    • 2020-12-01
    • 2021-07-07
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多