Goran
Goran

Reputation: 6518

EF Linq projection of nested collections - building relationship

I am having a two level nested child collections, which I project into DTOs. My question would also apply to a regular parent-> children relationship:

// There are two types on Parent and two types of Child classes,
// one is EF model, and another is DTO (here I show only one, for simplicity)
public class Parent
{
    public int Id {get;set;}
    public IEnumerable<Child> Children {get;set;}
}

public class Child
{
    public int Id {get;set;}
    public Parent Parent {get;set;}
}

var list = context.Set<Parent>().Select(p=> new DTO.Parent
    {
        Id = p.Id
        Children = (p.Children.Select(c=> new DTO.Child
            {
                Id=c.Id,
                Parent = ?
            }))
    });

Is it possible to assign a parent reference to child object while doing projection?

Upvotes: 0

Views: 917

Answers (2)

Slauma
Slauma

Reputation: 177163

I don't think it's possible to set the Parent directly in the query. So, here is only another workaround, sort of a "DTO relationship fixup":

public class Parent
{
    public int Id {get;set;}

    private IEnumerable<Child> _children;
    public IEnumerable<Child> Children
    {
        get { return _children; }
        set
        {
            _children = value;
            if (_children != null)
                foreach (var child in _children)
                    child.Parent = this;
        }
    }
}

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

You can do mapping with Automapper by eagar-loading children:

Mapper.CreateMap<Parent, DTO.Parent>();
Mapper.CreateMap<Child, DTO.Child>();
var list = Mapper.Map<IEnumerable<DTO.Parent>>(context.Set<Parrent>()
                                                      .Include(p => p.Children)
                                                      .AsEnumerable());

Automapper will map each entity to dto, and provide references to dto parent instance for each dto child.

Upvotes: 1

Related Questions