Graham Charles
Graham Charles

Reputation: 9632

Can I ignore Automapper properties on a one-off basis?

I am using Automapper to map EF objects to DTOs; many of the objects are in many-to-many arrangements. For example:

committee (table) 1 =< m  committeemember (table)  m >= 1 person (table)

That might map to:

public class CommitteeViewModel
{
    public int idCommittee { get; set; }
    public IEnumerable<CommitteeMemberViewModel> CommitteeMembers { get; set; }
}

public class CommitteeMemberViewModel
{
    public int idCommittee { get; set; }
    public int idCommitteeMember { get; set; }
    public PersonViewModel Members { get; set; }
}

And there are Automapper maps for <committee, CommitteeViewModel>, <committeemember, CommitteeMemberViewModel>, and <person, PersonViewModel>.

All is well when I want to return a single committee and its members.

BUT, when I want a list of committees without members, is there a way to ask Automapper to ignore certain properties, just for that call? Sort of like:

var committeeList = Automapper.Mapper.Map
    <List<committee>, List<CommitteeViewModel>>(committees)
   .Ignore("CommitteeMembers");

Of course, I can create new DTOs that omit these properties and map to those, but since I essentially want everything but one property, I thought there might be a better way, like creating a different map -- but I'm not managing to find it.

Thanks,

g.

Upvotes: 3

Views: 1161

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

You can achieve desired result this way: create new mapping (i.e. overwrite existing one), map your source entities, and override mapping back:

Mapper.CreateMap<committee, CommitteeViewModel>()
      .ForMember(c => c.CommitteeMembers, o => o.Ignore());

var committeeList = Mapper
      .Map<List<committee>, List<CommitteeViewModel>>(committees);

Mapper.CreateMap<committee, CommitteeViewModel>();

But I think it's better to keep things consistent. If I do mapping from committee to CommitteeViewModel I expect it will produce same result each time. So, it's better to create new view model for 'light' version of mapping.

Upvotes: 2

Related Questions