使用C#和Linq-to-entities映射复杂对象

时间:2018-11-21 15:14:22

标签: c# entity-framework linq-to-entities

我有两个Domain类:

var ParentClass
{
    public Guid Id { get; set; }
    public virtual IEnumerable<ChildClass> Children { get; set; }
}
var ChildClass
{
    public Guid Id { get; set; }
    public Guid ParentId { get; set; }
    public virtual ParentClass Parent{ get; set; }
}

如何获取将其及其所有子级映射到两个预定义视图模型(“ PClass”映射ParentClass和“ ChClass”映射ChildClass)的ParentClass列表?

我尝试了这段代码,但似乎不起作用:

var query = MyDataContext.ParentClasses.Select(x => new PClass
{
    Id = x.Id,
    Children = x.Children.Select(y => new ChClass // this select is not working
    {
        Id = y.Id,
        ParentId = y.ParentId,
        Parent = x // x is not the right type and it should be of type 'PClass'
    })
}).ToList();

1 个答案:

答案 0 :(得分:1)

如果每个PClass具有零个或多个子代,则填充每个Child类的父代是没有用的,因为您已经知道它是PClass。

此外,ChildClass中的该父级中至少有一个带有PClass的子级,当然,其中至少有一个子级与父级的子级,至少有一个子级具有父级的子级,...什么时候要停止吗?

因此,在这种情况下,我们要么不向父对象提供属性,要么为它提供空值:

var query = MyDataContext.Parents.Select(parent => new PClass
{
    Id = parent.Id,
    Children = parent.Children.Select(child => new ChClass
    {
        Id = child.Id,
        // ParentId = y.ParentId, Useless, you know it has the same value as Id
        // Parent = ... useless, you know it has the same value as the parent
        // that you are creating.
    })
    .ToList(),
});