不同数据类型之间的自动映射器映射

Automapper mapping between different datatypes

我有下面一段代码,我必须将 user.email(字符串数据类型)映射到 userProfile.Email.email 数据成员。

user.UserEmails.Add(new UserEmail { Email = email });

我该如何做这个映射?

下面是实体到模型映射的核心逻辑。希望对你有帮助

Mapper.CreateMap<SourceDataType, DestinationDataType>();
var YourEntityData = GetMyData();//this method will return data of type "SourceDataType"
DestinationDataType modelObj= 
              Mapper.Map<SourceDataType, DestinationDataType>(YourEntityData); 

假设您有 User class:

class User
{
    public string Email { get; set; }
}

和class UserProfile和class Email:

class UserProfile
{
    public Email Email { get; set; }
}

class Email
{
    public string Email { get; set; }
}

然后您可以执行以下操作:

// create mapping
Mapper.CreateMap<User, UserProfile>()
      .ForMember(up => up.Email, opt => opt.MapFrom(u => new UserEmail { Email = u.Email }));

// map the entity
var userProfile = Mapper.Map<UserProfile>(user); 

希望对您有所帮助。