Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper define mapping level

Tags:

c#

automapper

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.

like image 737
filur Avatar asked Jun 04 '17 10:06

filur


People also ask

What is AutoMapper configuration?

What is AutoMapper? AutoMapper is a simple library that helps us to transform one object type into another. It is a convention-based object-to-object mapper that requires very little configuration. The object-to-object mapping works by transforming an input object of one type into an output object of a different type.

Does AutoMapper use Reflection?

When you call CreateMap, AutoMapper uses optimizers to build the code for getting/setting values on source/destination types. Currently, it uses a combination of Reflection. Emit and expression tree compilation. At Map time, it uses the optimized callbacks for interacting with types.


1 Answers

You can define map specific MaxDepth like:

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

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

like image 82
Mauricio Gracia Gutierrez Avatar answered Sep 25 '22 11:09

Mauricio Gracia Gutierrez