0

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)));
9
  • You should create two different DTO types for your entity. Commented Feb 17, 2017 at 19:05
  • so no other solution :( ? Commented Feb 17, 2017 at 19:14
  • Why do you not want to create separate DTOs? Commented Feb 17, 2017 at 19:14
  • I was checking whether I can avoid a duplicate class creation Commented Feb 17, 2017 at 19:16
  • What AM method are you using for mapping? e.g. Map, ProjectTo etc.? Commented Feb 17, 2017 at 19:17

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.