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

时间:2016-05-06 12:49:51

标签: c# .net asp.net-mvc automapper

我有以下代码,我必须使用userProfile.Email.email datamember映射user.email(字符串数据类型)。

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

我怎么能做这个映射?

2 个答案:

答案 0 :(得分:1)

让我们说你有User班级:

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

以及班级UserProfile和班级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); 

希望它会有所帮助。

答案 1 :(得分:-1)

这是从实体到模型的映射的核心逻辑。希望它有所帮助

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