AutoMapper:将模型中的IList映射到viewModel中的IEnumerable

时间:2013-01-16 20:09:06

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

是否可以将Group中的IList映射到GroupViewModel中的IEnumerable?

模型

public class Group
{
    public string Name { get; set; }
    public virtual IList<Permission> Permissions
    {
        get { return _permissoes ?? (_permissions = new List<Permission>()); }
        set { Permissoes.Clear(); _permissions = value; }
    }
}

public class Permission
{
    public long Id { get; set; }
    public string Name { get; set; }
}

视图模型

public class GroupViewModel
{
    public string Name { get; set; }
    public IEnumerable<PermissionViewModel> Permissions { get; set; }
}

public class PermissionViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

1 个答案:

答案 0 :(得分:3)

简单:

var grp = new Group {Permissions = new List<Permission>{new Permission{Name="Permission 1"}, 
                                                       {new Permission{Name="Permission 2"}}}};

Mapper.CreateMap<Permission, PermissionViewModel>();

Mapper.CreateMap<Group, GroupViewModel>();


var result = Mapper.Map<GroupViewModel>(grp);