Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 238
Graham Charles Avatar asked Dec 10 '25 07:12

Graham Charles


1 Answers

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.

like image 148
Sergey Berezovskiy Avatar answered Dec 13 '25 20:12

Sergey Berezovskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!