简单的自动映射器示例 [英] Simple Automapper Example

查看:45
本文介绍了简单的自动映射器示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解如何映射某些对象.请回答有关这个简单示例的一些问题.

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>();

当将Group映射到GroupDto时,是否需要在内部将User映射到UserDto,因为Group 中的 >List 由未映射的 Users 组成?如果是这样,你怎么做?我的猜测是

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- 将 GroupD 更改为如下所示:

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- 创建您的映射:

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- 就是这样,因为自动映射器会自动将 List 映射到 List(因为它们具有相同的名称,并且已经存在从用户到 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);

希望有所帮助.

这篇关于简单的自动映射器示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆