簡體   English   中英

如何使用自動映射器有條件地將目標對象設置為null

[英]How do I conditionally set the destination object to null using automapper

我正在嘗試做這樣的事情:

AutoMapper.Mapper.CreateMap<UrlPickerState, Link>()
        .ForMember(m=>m.OpenInNewWindow,map=>map.MapFrom(s=>s.NewWindow))
        .AfterMap((picker, link) => link = !string.IsNullOrWhiteSpace(link.Url)?link:null) ;

var pickerState = new UrlPickerState();
var linkOutput = AutoMapper.Mapper.Map<Link>(pickerState);

但是, link的分配值未在任何執行路徑中使用。
我希望linkOutput為null,但不是。
如何使目標對象為空?

涉及對象的詳細信息:

public class Link
{
    public string Title { get; set; }
    public string Url { get; set; }
    public bool OpenInNewWindow { get; set; }
}

public class UrlPickerState
{
    public string Title { get; set; }
    public string Url { get; set; }
    public bool NewWindow { get; set; }
    //.... etc
}

這是一個小提琴: http : //dotnetfiddle.net/hy2nIa

這是我最后使用的解決方案,內部使用了更多手動信息,但不需要任何額外的設置。

如果有人有更優雅的解決方案,將不勝感激。

config.CreateMap<UrlPickerState, Link>()
            .ConvertUsing(arg =>
            {
                if (string.IsNullOrWhiteSpace(arg.Url))
                {
                    return null;
                }
                return new Link()
                {
                    Url = arg.Url,
                    OpenInNewWindow = arg.NewWindow,
                    Title = arg.Title,
                };
            });

我認為這將必須在映射之外完成。 由於AutoMapper需要實例進行映射,因此將目標設置為null似乎應該超出映射范圍。

我會做類似的事情:

AutoMapper.Mapper.CreateMap<UrlPickerState, Link>()
        .ForMember(m=>m.OpenInNewWindow,map=>map.MapFrom(s=>s.NewWindow));

var pickerState = new UrlPickerState();
Link linkOutput = null;
if(!string.IsNullOrWhiteSpace(pickerState.Url))  // or whatever condition is appropriate
    linkOutput = AutoMapper.Mapper.Map<Link>(pickerState);

我創建了以下擴展方法來解決此問題。

public static IMappingExpression<TSource, TDestination> PreCondition<TSource, TDestination>(
   this IMappingExpression<TSource, TDestination> mapping
 , Func<TSource, bool> condition
)
   where TDestination : new()
{
   // This will configure the mapping to return null if the source object condition fails
   mapping.ConstructUsing(
      src => condition(src)
         ? new TDestination()
         : default(TDestination)
   );

   // This will configure the mapping to ignore all member mappings to the null destination object
   mapping.ForAllMembers(opt => opt.PreCondition(condition));

   return mapping;
}

對於有問題的情況,可以這樣使用:

Mapper.CreateMap<UrlPickerState, Link>()
      .ForMember(dest => dest.OpenInNewWindow, opt => opt.MapFrom(src => src.NewWindow))
      .PreCondition(src => !string.IsNullOrWhiteSpace(src.Url));

現在,如果條件失敗,則映射器將返回null;否則,映射器將返回null。 否則,它將返回映射的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM