Gra*_*ham 10 .net c# automapper
我有两个实体和两个DTO.我正在将实体映射到DTO.DTO的简化版本如下所示:
public class FooDto {
// Other properties removed for clarity.
public string Description { get; set; }
public decimal Total { get; set; }
public ICollection<BarDto> Bars { get; set; }
}
public class BarDto {
// Other properties removed for clarity.
public decimal Total { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这些Foo和Bar类是:
public class Foo {
public ICollection<Bar> Bars { get; set; }
}
public class Bar {
// Unimportant properties
}
Run Code Online (Sandbox Code Playgroud)
映射
我在一个方法中将其映射为:
public FooDto Map(IMapper mapper, Foo foo) {
// _fooTotalService and _barTotalService injected elsewhere by DI.
return mapper.Map<Foo, FooDto>(foo, opt =>
{
opt.AfterMap((src, dest) =>
{
dest.Total = _fooTotalService.GetTotal(src);
dest.Bars.Total = ?????? // Needs to use _barTotalService.CalculateTotal(bar)
});
});
}
Run Code Online (Sandbox Code Playgroud)
AutoMapper已经配置了Foo到FooDto和Bar到BarDto的映射,它们正常工作.
我需要使用服务更新FooDto中的每个BarDto(其原因太长而无法进入 - 足以说它需要以这种方式发生).
我需要使用什么语法AfterMap来映射使用该方法的每个Total属性,哪里有问题? BarDto_barTotalService.CalculateTotal(bar)barBar
请注意,该_barTotalService.CalculateTotal方法采用的是Barnot 的实例BarDto.
Ami*_*osh 15
这应该工作 -
AutoMapper.Mapper.CreateMap<Foo, FooDto>()
.AfterMap((src, dest) =>
{
dest.Total = 8;//service call here
for (var i = 0; i < dest.Bars.Count; i++)
{
dest.Bars.ElementAt(i).Total = 9;//service call with src.Bars.ElementAt(i)
}
});
AutoMapper.Mapper.CreateMap<Bar, BarDto>();
var t = AutoMapper.Mapper.Map<FooDto>(new Foo
{
Bars = new List<Bar> { new Bar { } }
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12522 次 |
| 最近记录: |