如何使用AutoMapper将多个子类映射到一个类中?

时间:2010-12-22 20:13:24

标签: c# viewmodel automapper subclass

假设我有三个类是基类的子类:

public class BaseClass
{
    public string BaseName { get; set; }
}

public class Subclass1 : BaseClass
{
    public string SubName1 { get; set; }
}

public class Subclass2 : BaseClass
{
    public string SubName2 { get; set; }
}

public class Subclass3 : BaseClass
{
    public string SubName3 { get; set; }
}

我想将这些映射到ViewModel类,如下所示:

public class ViewModel
{
    public string BaseName { get; set; }
    public string SubName1 { get; set; }
    public string SubName2 { get; set; }
    public string SubName3 { get; set; }
}

ViewModel只是将所有子类的属性组合在一起并展平它。我尝试像这样配置映射:

AutoMapper.CreateMap<BaseClass, ViewModel>();

然后我尝试从我的数据库中抓取数据,如下所示:

var items = Repo.GetAll<BaseClass>();
AutoMapper.Map(items, new List<ViewModel>());

然而,最终发生的事情是BaseName中只会填充ViewModel属性。我如何配置AutoMapper以便它也将映射子类中的属性?

2 个答案:

答案 0 :(得分:13)

AutoMapper中似乎存在一个错误或限制,您需要相应的TSource和TDestination层次结构。给出:

public class BaseClass {
    public string BaseName { get; set; }
}

public class Subclass1 : BaseClass {
    public string SubName1 { get; set; }
}

您需要以下视图模型:

public class ViewModel {
    public string BaseName { get; set; }
}
public class ViewModel1 : ViewModel {
    public string SubName1 { get; set; }
}

以下代码可以使用:

 Mapper.CreateMap<BaseClass, ViewModel>()
       .Include<Subclass1, ViewModel1>();
 Mapper.CreateMap<Subclass1, ViewModel1>();

 var items = new List<BaseClass> {new Subclass1 {BaseName = "Base", SubName1 = "Sub1"}};
 var viewModels = Mapper.Map(items, new List<ViewModel>());

答案 1 :(得分:1)

试试这个:

AutoMapper.CreateMap<BaseClass, ViewModel>()
  .Include<Subclass1, ViewModel>()
  .Include<Subclass2, ViewModel>()
  .Include<Subclass3, ViewModel>();
AutoMapper.CreateMap<Subclass1, ViewModel>();
AutoMapper.CreateMap<Subclass2, ViewModel>();
AutoMapper.CreateMap<Subclass3, ViewModel>();

var items = Repo.GetAll<BaseClass>();
AutoMapper.Map(items, new List<ViewModel>());