Examples:
There are two ways and it’s them:
1) First form
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 don’t want the Automapper bring the list of people’s phones and then my receiving class will be like this:
public class PeopleView
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual DateTime? DateNasc { get; set; }
}
I mean, she doesn’t have the phone list and so the Automapper will only bring what I set in 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);
Threshing:
Data of a class
Data from a collection
2) Second form
You can also create a rule on Automapper talking to him 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; }
}
Configuring the Automapper
AutoMapper.Mapper.CreateMap(typeof(People), typeof(PeopleView))
.ForMember("Phone", x => x.Ignore());
Automatically it will ignore the phone list as demonstrated in the image below:
Demo
https://dotnetfiddle.net/99Zqlf
References:
Cezar, I’ll do what you said and see how it will stay here. As soon as I modify I’ve worked out.
– Flavio Vissoto
Cezar, Sorry the delay to answer kkk, I was performing the tests. Gave certinho... I will continue the application and if further ahead I come across another problem I warn. Thank you so much for the help.
– Flavio Vissoto