Dileep Paul
Dileep Paul

Reputation: 167

How can we create different mapping for same entity in automapper

I need to write mapping for an entity to its DTO for listing purpose and details view of an entity. But for listing I need to ignore a list property because of DTO because I don't want to load it, I have enabled Lazy loading in Entity framework. How can I create two mappings of same entity or add ignore for a property while querying data for list view.

cfg.CreateMap<page, PageViewModel>().ForMember(t => t.PageRows, opts => opts.MapFrom(s => s.page_rows)).
            ForMember(t => t.PageRules, opts => opts.MapFrom(s => s.page_rules.Select(x => x.rule_id)));

cfg.CreateMap<page, PageViewModel>().ForMember(t => t.PageRows, opts => opts.Ignore()).
            ForMember(t => t.PageRules, opts => opts.MapFrom(s => s.page_rules.Select(x => x.rule_id)));

Upvotes: 0

Views: 1713

Answers (2)

Ivan Stoev
Ivan Stoev

Reputation: 205769

You can setup a Precondition with Func<ResolutionContext, bool> and then use the Map method overloads with Action<IMappingOperationOptions> to pass the controlling parameter through Items dictionary.

For instance:

.ForMember(t => t.PageRows, opts => 
{
     opts.MapFrom(s => s.page_rows);
     opts.PreCondition(context => !context.Items.ContainsKey("IgnorePageRows"));
})

and then:

IEnumerable<page> source = ...;
var withPageRows = Mapper.Map<List<PageViewModel>>(source);
var noPageRows = Mapper.Map<List<PageViewModel>>(source, 
    opts => opts.Items.Add("IgnorePageRows", null));

Reference: Conditional mapping

Upvotes: 2

Stout01
Stout01

Reputation: 1126

You would have to create two different DTO classes to map to. If you do not want to do that, you also have another option which would be to create two marker interfaces and map to those.

Upvotes: 1

Related Questions