将 Automapper 与抽象对象的集合一起使用

Using Automapper with a collection of abstract objects

请看看我正在尝试做的这个相当人为的例子。

一、数据库型号:

public class Report
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Worker> Workers { get; set; } 
}

public abstract class Worker
{
    public Guid Id { get; set; }
}

public class Fireman : Worker
{
    public string Station { get; set; }
}

public class Cleaner : Worker
{
    public string FavoriteSolvent { get; set; }
}

现在视图模型:

public class AddReportViewModel
{
    public string Name { get; set; }
    public List<AddFiremanViewModel> Firemen { get; set; }
    public List<AddCleanerViewModel> Cleaners { get; set; }
}

public class AddFiremanViewModel
{
    public string Station { get; set; }
}

public class AddCleanerViewModel
{
    public string FavoriteSolvent { get; set; }
}

最后是 Automapper 配置文件:

public class ReportProfile : Profile
{
    protected override void Configure()
    {
        CreateMap<AddReportViewModel, Report>();
        CreateMap<AddFiremanViewModel, Fireman>();
        CreateMap<AddCleanerViewModel, Cleaner>();
    }
}

我希望 FiremenCleaners 都填充 Workers 集合,这是一个 ICollection<Worker>。我希望这是有道理的。我该怎么做?

您的视图模型不包含任何 Id 字段,因此我在映射中将它们设置为 Ignore。然后,我只是使用 LINQ 的 Union 子句将两个源列表组合成一个集合(在使用 Automapper 转换每个列表之后)。这是映射:

Mapper.CreateMap<AddReportViewModel, Report>()
    .ForMember(d => d.Id, o => o.Ignore())
    .ForMember(d => d.Workers, o => o.MapFrom(
        s => Mapper.Map<ICollection<AddFiremanViewModel>, ICollection<Fireman>>(s.Firemen)
            .Union<Worker>(Mapper.Map<ICollection<AddCleanerViewModel>, ICollection<Cleaner>>(s.Cleaners))))
    ;
Mapper.CreateMap<AddFiremanViewModel, Fireman>()
    .ForMember(d => d.Id, o => o.Ignore())
    ;
Mapper.CreateMap<AddCleanerViewModel, Cleaner>()
    .ForMember(d => d.Id, o => o.Ignore())
    ;

这是一个使用它的例子:

var vm = new AddReportViewModel
{
    Name = "Sample",
    Cleaners = new List<AddCleanerViewModel>
    {
        new AddCleanerViewModel {FavoriteSolvent = "Alcohol"}
    },
    Firemen = new List<AddFiremanViewModel>
    {
        new AddFiremanViewModel {Station = "51"},
        new AddFiremanViewModel {Station = "49"}
    }
};

var db = Mapper.Map<AddReportViewModel, Report>(vm);