我希望将DTO映射到DBO模型期间的空值被忽略。这是代码:
DTO / DBO模型都具有两个名为项目的属性:
applyAsync
DBO构造函数:
public virtual ICollection<price_list_item> items { get; set; }
DTO构造函数没有属性初始化
public price_list()
{
this.items = new List<price_list_item>();
}
AutoMapper配置文件:
public price_list()
{
}
API控制器:
this.CreateMap<DTO.price_list, DBO.price_list>()
.ForMember(m => m.id, src => src.Ignore())
.ForMember(m => m.currency_id, src => src.MapFrom(f => f.currency))
.ForMember(dest => dest.items, opt => opt.Condition(src => (src.items != null)))
当我向API发送没有任何'items'属性符号的JSON时,控制台输出为:
[HttpPut]
[Route("{id:long}")]
public async Task<DTO.price_list> UpdateOneAsync(long id, [FromBody]DTO.price_list payload)
{
if (payload == null)
{
throw new ArgumentNullException("payload");
}
Console.WriteLine(payload.items == null);
var _entity = await this.IDataRepository.price_lists
.Where(w => w.id == id)
.Include(i => i.items)
.FirstOrDefaultAsync();
if (_entity == null)
{
NotFound();
return null;
}
Console.WriteLine(_entity.items.Count);
// map fields to existing model
this.IMapper.Map<DTO.price_list, DBO.price_list>(payload, _entity);
Console.WriteLine(_entity.items.Count);
我在做什么错?为什么条件没有得到遵守,item属性没有被“跳过”?
谢谢
答案 0 :(得分:0)
Lucian,谢谢, PreCondition 解决了该问题。这是有效的代码:
this.CreateMap<DTO.price_list, DBO.price_list>()
.ForMember(m => m.id, src => src.Ignore())
.ForMember(m => m.currency_id, src => src.MapFrom(f => f.currency))
.ForMember(dest => dest.items, opt => opt.PreCondition(src => (src.items != null)))