简单的例子Automapper [英] Simple Automapper Example
问题描述
我有一个很难理解如何特定对象映射。请回答这个简单的例子一些问题。
I am having a hard time to understand how to map certain objects. Please answer some questions about this simple example.
的示例代码的
class User
{
private int id;
private string name;
}
class Group
{
private int id;
private string name;
private List<User> users;
}
[DataContract]
public class UserDto
{
[DataMember]
public int id { get; set; }
[DataMember]
public string name{ get; set; }
}
[DataContract]
public class GroupDto
{
[DataMember]
public int id { get; set; }
[DataMember]
public string name{ get; set; }
[DataMember]
public List<User> Users { get; set; }
}
的的映射器的
Mapper.CreateMap<User, UserDto>();
Mapper.CreateMap<UserDto, User>();
Mapper.CreateMap<Group, GroupDto>();
Mapper.CreateMap<GroupDto, Group>();
在映射组
到 GroupDto
,你有地图用户
到 UserDto
内部因为列表<使用者>
在组
包括映射的用户
?如果是的话,你怎么办呢?我的猜测是
When mapping Group
to GroupDto
, do you have to map User
to UserDto
internally because the List<User>
in Group
consist of unmapped Users
? If so how do you do this? My guess is
Mapper.CreateMap<Group, GroupDto>()
.ForMember(g => g.id, opt => opt.Ignore());
.ForMember(g => g.name, opt => opt.Ignore());
.ForMember(g => g.Users, opt => opt.MapFrom(u => Mapper.Map<Group, UserDto>(u)))
这是正确的?
推荐答案
1更改GroupDto是这样的:
1- Change the GroupDto to be like this:
[DataContract]
public class GroupDto
{
[DataMember]
public int id { get; set; }
[DataMember]
public string name{ get; set; }
[DataMember]
public List<UserDTO> Users { get; set; }
}
2 - 创建映射:
2- Create your mappings :
Mapper.CreateMap<User, UserDto>();
Mapper.CreateMap<UserDto, User>(); // Only if you convert back from dto to entity
Mapper.CreateMap<Group, GroupDto>();
Mapper.CreateMap<GroupDto, Group>(); // Only if you convert back from dto to entity
3这一切,因为自动映射器会自动映射列表<使用者>
到列表< UserDto>
(因为它们具有相同的名称,并且已经有一个映射从用户到UserDto)
3- that's all, because auto mapper will automatically map the List<User>
to List<UserDto>
(since they have same name, and there is already a mapping from user to UserDto)
4-当你想映射你拨打:
4- When you want to map you call :
Mapper.Map<GroupDto>(groupEntity);
希望有所帮助。
Hope that helps.
这篇关于简单的例子Automapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!