Examples:
There are two ways and they are:
1) First way
In these two People and Phone classes (1 person can have multiple phones),
public class People
{
public People()
{
Phone = new HashSet<Phone>();
}
public People(int id, string name, DateTime? datenasc)
{
Id = id;
Name = name;
DateNasc = datenasc;
Phone = new HashSet<Phone>();
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual DateTime? DateNasc { get; set; }
public virtual ISet<Phone> Phone { get; set; }
}
public class Phone
{
public Phone() { }
public Phone(int id, string ddd, string number, People people)
{
Id = id;
Ddd = ddd;
Number = number;
People = people;
}
public virtual int Id { get; set; }
public virtual string Ddd { get; set; }
public virtual string Number { get; set; }
public virtual People People { get; set; }
}
I do not want Automapper to bring the list of people's phones and my receiving class will look like this:
public class PeopleView
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual DateTime? DateNasc { get; set; }
}
That is, it does not have the phone list and so the Automapper will only bring what I have defined in the class PeopleView
.
How to use:
AutoMapper.Mapper.CreateMap(typeof(People), typeof(PeopleView));
PeopleView peopleView = AutoMapper.Mapper.Map<PeopleView>(people);
//COLEÇÃO
List<People> Pessoas = con.ToList<People>();
AutoMapper.Mapper.CreateMap(typeof(People), typeof(PeopleView));
var peoplesview = AutoMapper.Mapper.Map<List<People>, List<PeopleView>>(Pessoas);
Debugging:
Data from a class
Datafromacollection
2)Secondway
Youcanalsocreatearulein Automapper talking to it ignore the list or lists, following the example of People class plus the change placed just below:
public class PeopleView
{
public PeopleView()
{
Phone = new HashSet<Phone>();
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual DateTime? DateNasc { get; set; }
public virtual ISet<Phone> Phone { get; set; }
}
Setting up Automapper
AutoMapper.Mapper.CreateMap(typeof(People), typeof(PeopleView))
.ForMember("Phone", x => x.Ignore());
Automatically it will ignore the phone list as shown in the image below:
Demo
link
References: