gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:26:28 24 4
gpt4 key购买 nike

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

首先是数据库模型:

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; }
}

现在是 View 模型:

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> .我希望这是有道理的。我该怎么做?

最佳答案

您的 View 模型不包含任何 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);

关于c# - 将 Automapper 与抽象对象的集合一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28636132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com