我有两个classe User(Destination)和UserViewModel(Source):
public class User
{
public int Id{ get; set; }
public string Username{ get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public Enums.Sex Sex { get; set; }
public byte[] ProfilePicture { get; set; }
public int Score { get; set; }
}
public class ProfileViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
}
这是AutoMapper配置:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ProfileViewModel, User>()
.ForMember<int>(u =>u.Id, m => m.Ignore()).ForMember<string>(u=> u.UserName, m => m.Ignore());
});
我在这里使用它:
public ActionResult MyProfile(ProfileViewModel m, HttpPostedFileBase profilePicture)
{
User currentUser = UserRep.GetCurrentUser(User.Identity.GetUserId());
currentUser = Mapper.Map<User>(m);
...
}
我为当前用户提供了所有数据ID,用户名...当我执行映射时,用户名为null且id = 0我知道并且我尝试使用ignore()和usedestinationValue()
答案 0 :(得分:2)
当您致电Mapper.Map(source)
时,AutoMapper将创建一个全新的对象并填充视图模型中的数据。它的行为类似于此代码
var temp = new User();
temp.FirstName = source.FirstName;
temp.LastName = source.LastName;
...
return temp;
看看没有来自原始用户对象的数据,并在下一步中覆盖对原始对象的引用。 您应该使用将现有对象作为参数的重载
public ActionResult MyProfile(ProfileViewModel m, HttpPostedFileBase profilePicture)
{
User currentUser = UserRep.GetCurrentUser(User.Identity.GetUserId());
currentUser = Mapper.Map<ProfileViewModel, User>(currentUser, m); // you can skip assign to variable
...
}
Mapper.Map(destination,source)
的行为类似于此代码
destination.FirstName = source.FirstName;
destination.LastName = source.LastName;
...
return source;