0

DTO에 투영되는 두 개의 레벨 중첩 된 자식 컬렉션이 있습니다. 내 질문은 정기적으로 학부모> 자녀 관계에 적용됩니다 :EF 중첩 컬렉션의 LINQ 투영 - 건물 관계

// 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 = ? 
      })) 
    }); 

가 투사하는 동안 자식 객체에 대한 부모의 참조를 할당 할 수 있습니까?

+0

물론 이것은 아직 목적이 아닙니까? 'Parent = p.Id' –

+0

@BeratBilgin 정확하게 말한 것을 이해하지 못합니다 ... – Goran

답변

0

Parent을 검색어에 직접 설정하는 것이 가능하지 않다고 생각합니다. 그래서, 여기에 또 다른 해결 방법, 일종의 "DTO 관계 픽스 업"이 있습니다 :

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; 
     } 
    } 
} 
1

당신은 eagar 로딩 아이들 Automapper로 매핑을 수행 할 수 있습니다

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는 DTO에 각 엔티티를 매핑하고, 각 DTO의 아이를 위해 DTO 부모 인스턴스에 대한 참조를 제공 할 것입니다.

+0

예, 그렇지만 그것은 수동으로 완전한 트리를 반복하는 것과 같습니다. 귀하의 대답은 Linq2Ent 투영을 사용하여 수행 할 수 없습니까? – Goran