public class Parent
{
public int ParentId { get; set; }
public string ParentPropertyA { get; set; }
public string ParentPropertyA { get; set; }
public List<Child> Children{get; set;}
}
public class Child
{
public int ChildId { get; set; }
public string ChildPropertyA { get; set; }
public string ChildPropertyB { get; set; }
}
private static Expression<Func<Parent, dynamic>> BuildModel()
{
return x => new
{
x.ParentId,
x.Children
};
}
我在IQueryable.Select(BuildModel())
我们说我有Parent
个对象,其中有两个Children
...
鉴于该结构,我如何实现返回包含所有Parent
属性和特定Children
的两个记录,而不只是一个Parent
和两个Children
?
示例:
{
ParentId: 1,
ParentPropertyA: "parentA",
ParentPropertyB: "parentB",
Children:
[
{
ChildId: 1,
ChildPropertyA: "childA1",
ChildPropertyB: "childB1"
},
{
ChildId: 2,
ChildPropertyA: "childA2",
ChildPropertyB: "childB2"
}
]
}
相反,我希望将它们作为:
返回[
{
ParentId: 1,
ParentPropertyA: "parentA",
ParentPropertyB: "parentB",
ChildId: 1,
ChildPropertyB: "childB1"
},
{
ParentId: 1,
ParentPropertyA: "parentA",
ParentPropertyB: "parentB",
ChildId: 2,
ChildPropertyB: "childB2"
}
]
这可能吗?谢谢!
答案 0 :(得分:4)
在父集合上使用SelectMany
。在SelectMany表达式中,选择子项,并将其与父项的副本配对。
var flattenedList = parents.SelectMany
(
p => p.Children.Select
(
c => new { Parent = p, Child = c }
)
);
这将为每个孩子提供一个元素,并根据需要复制父母。
答案 1 :(得分:0)
DTO课程:
public class DTO
{
public int ParentId { get; set; }
public string ParentPropertyA { get; set; }
public string ParentPropertyB { get; set; }
public int ChildrenId { get; set; }
public string ChildrenPropertyB { get; set; }
}
用法:
var parent = GetParent() //Get Parent instance
List<Dto> dtos = parent.Childrens.Select(q => new DTO
{
ParentId = parent.ParentId,
ParentPropertyA = parent.ParentPropertyA
ParentPropertyB = parent.ParentPropertyB,
ChildrenId = q.ChildrenId,
ChildrenPropertyB = q.ChildrenPropertyB
})
.ToList();