I use AutoMapper for mapping classes. I am struggling with the Automapper syntax. I have domain classes:
public class Club
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime OpenDate { get; set; }
public IEnumerable<Team> Teams { get; set; }
}
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public IEnumerable<Player> Players { get; set; }
}
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
Also i have dto classes:
public class ClubDTO
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime OpenDate { get; set; }
public IEnumerable<Team> TeamsDTO { get; set; }
}
public class TeamDTO
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public IEnumerable<Player> PlayersDTO { get; set; }
}
public class PlayerDTO
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
I have mapping setting from DTO classes in domain classes:
CreateMap<PlayerDTO, Player>();
CreateMap<TeamDTO, Team>();
CreateMap<ClubDTO, Club>();
I map ClubDTO
class to Club
:
...
_mapper.Map(clubDto, club);
...
How do I setting mapping only Player.Age
and Player.Addres
instead of all fields all classes?
I believe you should ignore whatever properties you wouldn't like to be mapped, like so:
CreateMap<PlayerDTO, Player>();
.ForMember(x => x.Id, x => x.Ignore())
.ForMember(x => x.Name, x => x.Ignore());
.ForMember(x => x.Surname , x => x.Ignore());
Take notice that this should be done during automapper configuration, not when you call the Map
method.
You should be able to do something like this: _mapper.Map(from, to).ForMember(x => x.MyProperty, opt => opt.Ignore());
I would also suggest using View Models
. This helps alot with AutoMapper
For example:
public class Player
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
public class PlayerViewModel
{
public int Id{get; set;
//more fields that you can use in your views
}
public class PlayerDTO
{
public int Age { get; set; }
public string Address { get; set; }
}
var onlyAgeAndAdress=_mapper.Map(Player, PlayerDTO);
you will get only ages and adresses.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.