【问题标题】:AutoMapper core Condition not workingAutoMapper 核心条件不起作用
【发布时间】:2018-07-13 11:40:18
【问题描述】:

我希望忽略将 DTO 映射到 DBO 模型期间的空值。这是代码:

DTO / DBO 模型具有两个名为 items 的属性:

public virtual ICollection<price_list_item> items       { get; set; }

DBO 构造函数:

public price_list()
{
    this.items = new List<price_list_item>();
}

DTO 构造函数没有属性初始化

public price_list()
{        
}

AutoMapper 配置文件:

 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 控制器:

[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);

当我向 API 发送一个没有任何“项目”属性迹象的 JSON 时,控制台输出是:

True
1200 // price list in dbo has 1200 items
0    // here I need to have still 1200 items

我做错了什么?为什么不遵守条件并且未“跳过”项目属性?

谢谢

【问题讨论】:

标签: c# .net-core automapper


【解决方案1】:

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)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 2018-11-02
    • 2018-03-23
    • 2011-02-19
    • 1970-01-01
    相关资源
    最近更新 更多