13
public class Foo
{
    public string Baz { get; set; }
    public List<Bar> Bars { get; set; }
}

When I map the class above, is there any way to define how deep I want automapper to map objects? Some pseudo code of what I'm after:

var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 0 });
// result = { Baz: "" }

var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 1 });
// result = { Baz: "", Bars: [{ Blah: "" }] }

 var mapped = Mapper.Map<FooDTO>(foo, opt => { levels: 2 });
// result = { Baz: "", Bars: [{ Blah: "", Buzz: [{ Baz: "" }] }] }

// etc...

I'm currently using automapper 3.3 due to a nuget dependency.

filur
  • 2,116
  • 6
  • 24
  • 47
  • There is no way to set levels in automapper even in latest version. Because You only deal with 1 level of hierarchy at a time. In your case you need 2 mapper configurations. One for `Foo` and second for `Bar`. You can use `opt.Ignore()` in your mapper configuration for any property which you do not want to map . Automapper does automatically map if the names of the objects are same or matching. I think in your case object names are different and you need configuration for each object. – Venkata Dorisala Jun 07 '17 at 09:06

2 Answers2

7

You can do it by providing a value at runtime as was answered in question: How to ignore a property based on a runtime condition?.

Configuration:

Mapper.CreateMap<Foo, FooDTO>().ForMember(e => e.Bars,
    o => o.Condition(c => !c.Options.Items.ContainsKey("IgnoreBars")));

Usage:

Mapper.Map<FooDTO>(foo, opts => { opts.Items["IgnoreBars"] = true; });

Same configuration approach you can apply for all your nested objects that you call levels.

If you want to achieve same behavior for your DB Entities you can use ExplicitExpansion approach as described in this answer: Is it possible to tell automapper to ignore mapping at runtime?.

Configuration:

Mapper.CreateMap<Foo, FooDTO>()
    .ForMember(e => e.Bars, o => o.ExplicitExpansion());

Usage:

dbContext.Foos.Project().To<FooDTO>(membersToExpand: d => d.Bars);
Andrii Litvinov
  • 12,402
  • 3
  • 52
  • 59
1

You can define map specific MaxDepth like:

Mapper.CreateMap<Source, Destination>().MaxDepth(1);

More info: https://github.com/AutoMapper/AutoMapper/wiki

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99