简体   繁体   English

AutoMapper和条件映射为null

[英]AutoMapper and conditional mapping to null

I want to create mapping like this: 我想创建这样的映射:

  • if the source property has it's Id == 0, set the destination property to null 如果源属性的Id == 0,则将目标属性设置为null

  • if the source property has it's Id != 0, map this property using default configuration 如果source属性具有Id!= 0,则使用默认配置映射此属性

For example: 例如:

Mapper.CreateMap<ItemViewModel, Item>()
    .ForMember(x => x.DestinationArticle, o => o.SetNullIfSourceHasIdZero(x => x.SourceArticle));

The DestinationArticle and SourceArticle properties are of implementing: DestinationArticle和SourceArticle属性的实现是:

public interface IEntity
{
    long Id { get; set }
}

My current solution is this: 我当前的解决方案是这样的:

.ForMember(x => x.DestinationArticle, o => o.MapFrom(x => x.SourceArticle != null && x.SourceArticle.Id != 0 ? Mapper.Map<Article>(x.SourceArticle) : null))

which is not so good and not generic. 这不是很好也不通用。

So, is there any way to create, mentioned before, SetNullIfSourceHasIdZero extension method or something, which could make my life easier? 那么,有没有办法创建前面提到的SetNullIfSourceHasIdZero扩展方法或其他方法,这可以使我的生活更轻松?

Try something along these lines.. 尝试以下方法。

Mapper.CreateMap<ItemViewModel, Item>()
    .ForMember(x => x.DestinationArticle, opt => opt.ResolveUsing<SetNullIfSourceHasIdZero>());

public class SetNullIfSourceHasIdZero : ValueResolver<ItemViewModel, DestinationArticle>
{
     protected override DestinationArticle ResolveCore(ItemViewModel item)
     {
        // logic here            
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM