Search code examples
c#automapper

How to ignore nested of nested objects with ProjectTo in Automapper?


Is it possible to ignore nested nested objects when loading lazily?

public class Parent
{
    public List<Child> Children;
}

public class Child
{
    public List<SomeObject> SomeObjects;
}

When defining Parent, you need to ignore the Someobject field inside Children, but when defining only Child, you don't need to ignore it.

Is this possible without adding a copy of Child class without a field? It is necessary not just to delete the object, but to ignore it during the SQL query.

//SomeObjects inside Child must be empty
var parent = _mapper.ProjectTo<ParentDTO>(_dbContext.Parent.Where(c => c.Id == id)).FirstOrDefault();

//not ignored SomeObjects inside Child
var child = _mapper.ProjectTo<ChildDTO>(_dbContext.Children.Where(c => c.Id == id)).FirstOrDefault();

Thanks for your time


Solution

  • Solved the following way

    CreateMap<Child, ChildDTO>
      .ForMember(_ => _.SomeObjects, opt => opt.ExplicitExpansion())
      .ForAllMembers(_ => _.UseDestinationValue());
    
    //calls
    var parent = _mapper.ProjectTo<ParentDTO>(_dbContext.Parents.Where(c => c.Id == id)).FirstOrDefault();
    
    var client = _mapper.ProjectTo<ChildDTO>(
                        _dbContext.Children.Where(c => c.Id == id),
                        null,                    
                        c => c.SomeObjects  //include SomeObjects
                    ).FirstOrDefault();