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