Dropdown的AutoMapper问题

时间:2011-04-14 17:47:04

标签: asp.net-mvc-3 automapper

我今天开始使用AutoMapper了... 但我对Dropdown模型有一些问题......

到目前为止我所拥有的:

用户模型

public class User : Entity
{          
    public virtual string Name { get; set; }   
    public virtual string Email { get; set; }
    public virtual string Password { get; set; } 
    public virtual Role Role { get; set; }      
}

角色模型

public class Role : Entity
{          
    public virtual string Name { get; set; }   
}

UserUpdateViewModel

public class UserUpdateViewModel
{
    public int Id{get;set;}

    [Required(ErrorMessage = "Required.")]
    public virtual string Name { get; set; }

    [Required(ErrorMessage = "Required."), Email(ErrorMessage = "Email Invalid."), Remote("EmailExists", "User", ErrorMessage = "Email already in use.")]
    public virtual string Email { get; set; }

    [Required(ErrorMessage = "Required.")]
    public virtual string Password { get; set; }

    [Required(ErrorMessage = "Required")]
    public virtual string ConfirmPassword { get; set; }

    [Required(ErrorMessage = "Required.")]
    public int RoleId { get; set; }

    public IList<Role> Roles { get; set; }
}

UserController中

public ActionResult Update(int id=-1)
{
      var _user = (_userRepository.Get(id));
      if (_user == null)
          return RedirectToAction("Index");

       Mapper.CreateMap<User, UserUpdateViewModel>();
       var viewModel = Mapper.Map<User, UserUpdateViewModel>(_user);

       viewModel.Roles = _roleRepository.GetAll();

       return View(viewModel);
}

[HttpPost, Transaction]
public ActionResult Update(UserViewModel user)
{
     if (ModelState.IsValid)
     {
         user.Password = _userService.GetPasswordHash(user.Password);

         Mapper.CreateMap<UserViewModel, User>();
         var model = Mapper.Map<UserViewModel, User>(user);  //model.Role = null

         _userRepository.SaveOrUpdate(model); //ERROR, because model.Role = null
         return Content("Ok");
     }
     return Content("Erro").         
}

查看更新

...
@Html.DropDownListFor(model => model.RoleId, new SelectList(Model.Roles, "Id", "Name"), "-- Select--", new { @class = "form radius" })   
...

一些考虑因素:
1 - 我返回Content()因为使用HTML 5 PushState等启用了所有Ajax 2 - 在我的更新(POST 1)方法中,Autommapper返回的模型具有Role = null

为什么Automapper返回的我的角色为空?
这是使用AutoMapper的正确方法吗?有提示吗?

由于

1 个答案:

答案 0 :(得分:3)

地图失败是因为您尝试将单个角色直接映射到角色集合。并将角色集合回单个角色。你不能直接映射它们,因为它们是不同的类型。

如果要将角色映射到列表,则可以使用自定义值解析器。

    Mapper.CreateMap<User , UserUpdateViewModel>()
    .ForMember(dest => dest.Roles, opt => opt.ResolveUsing<RoleToCollectionResolver>())


    Public class RoleToCollectionResolver: ValueResolver<User,IList<Role>>{ 
        Protected override IList<Role> ResolveCore(User source){
            var roleList = new List<Role>();
            roleList.Add(source.Role);
            Return roleList;
    }
}