【问题标题】:Automapper : UseDestinationValue() and Ignore() methode aren't workingAutomapper:UseDestinationValue() 和 Ignore() 方法不起作用
【发布时间】:2017-10-29 20:15:56
【问题描述】:

我有两个类 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()

【问题讨论】:

    标签: c# asp.net automapper


    【解决方案1】:

    当您调用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;
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2011-11-26
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 2017-06-09
    相关资源
    最近更新 更多