Automapper:UseDestinationValue()和Ignore()方法不起作用 [英] Automapper : UseDestinationValue() and Ignore() methode aren't working

查看:39
本文介绍了Automapper:UseDestinationValue()和Ignore()方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类User(目标)和UserViewModel(源):

i have two classe User (Destination) and 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配置:

This is the AutoMapper config :

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

I bring the current user with all the data id, username ... and when i execute the mapping username is null and id = 0 i d'ont understand and i try with ignore() and usedestinationValue()

推荐答案

调用 Mapper.Map(source)时,AutoMapper将创建一个全新的对象并填充视图模型中的数据.它的行为与此代码类似

When you call Mapper.Map(source) AutoMapper will create a brand new object and fill with data from view model. Its behaves similarly to this code

var temp = new User();
temp.FirstName = source.FirstName;
temp.LastName = source.LastName;
...
return temp;

查看原始用户对象中没有数据,然后在下一步中覆盖对原始对象的引用.您应该使用将现有对象作为参数的重载

Look there is no data from orginal user object, and in next step you overwrite reference to orginal object. You should use the overload that takes the existing object as a parameter

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;

这篇关于Automapper:UseDestinationValue()和Ignore()方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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