2016-08-01 67 views
3

我有下面的代码已经在Automapper的v3中工作,但不再在v5中。 更新它也适用于v4。Automapper v5升级后的空属性值

CallScheduleProfile在其构造函数中将Title属性设置为类的实例,该实例将值true传递给它。

CallScheduleProfileViewModel在其构造设置一个Title属性到该传递的true"Title"的值的不同的类的实例。

我已经在AutoMapper中为所有4个类设置了映射,然后我调用Map。

的结果是,该地图后Title财产上CallScheduleProfileViewModeltrue一个布尔值,但FriendlyName是空的,即使它在它的构造函数的设定。

我认为正在发生的事情是,在CallScheduleProfileViewModel构造函数被调用,FriendlyName被越来越赋予但是当映射发生时呼吁Entry的构造函数,然后任何属性映射上UxEntry存在,并指定该到​​Title财产和默认FriendlyName将为空,因为FriendlyName不存在UxEntry它的值不被复制。

我可能在这个假设中是错误的,但是无论哪种方式,我如何在映射上填充FriendlyName

更新:我查看了嵌套类型的Automapper documentation,问题也存在于文档中提供的代码中。如果我将一个字符串属性添加到InnerDest并将其值设置为OuterDest的构造函数,则Map之后其值为空。

A)构造Entry<T>类型此属性设置为null

B)Automapper后产生的Entry<T>一个新实例():

public static void Main(string[] args) 
{ 
    Mapper.Initialize(cfg => 
    { 
     cfg.CreateMap<UxEntry<bool>, Entry<bool>>(); 

     cfg.CreateMap<CallScheduleProfile, CallScheduleProfileViewModel>(); 
    }); 

    var old = new CallScheduleProfile(); 

    var newmodel = Mapper.Map<CallScheduleProfile, CallScheduleProfileViewModel>(old); 

    Console.WriteLine(newmodel.Title.Value); 
    Console.WriteLine(newmodel.Title.FriendlyName); 
} 

public class UxEntry<T> 
{ 
    public static implicit operator T(UxEntry<T> o) 
    { 
     return o.Value; 
    } 

    public UxEntry() 
    { 
     this.Value = default(T); 
    } 

    public UxEntry(T value) 
    { 
     this.Value = value; 
    } 

    public T Value { get; set; } 
} 


public class CallScheduleProfile 
{ 
    public CallScheduleProfile() 
    { 
     this.Title = new UxEntry<bool>(true); 
    } 

    public UxEntry<bool> Title { get; set; } 

} 

public class Entry<T> 
{ 
    public Entry() 
    { 
    } 

    public Entry(T value, string friendlyName) 
    { 
     this.Value = value; 
     this.FriendlyName = friendlyName; 
    } 

    public T Value { get; set; } 
    public string FriendlyName { get; set; } 

    public static implicit operator T(Entry<T> o) 
    { 
     return o.Value; 
    } 
} 


public class CallScheduleProfileViewModel 
{ 
    public CallScheduleProfileViewModel() 

    { 
     this.Title = new Entry<bool>(true, "Title"); 
    } 
    public Entry<bool> Title { get; set; } 
} 

回答

0

好,Automapper因为这个属性null地图!调用CallScheduleProfileViewModel中的构造函数。

C)有用于Automapper

没有设定其他规则

什么,你可以在这里做的是改变配置,让你让Automapper知道应该使用的一个属性的默认值:

 Mapper.Initialize(cfg => 
     { 
      // when UxEntry is mapped to Entry value "Title" is used for property FriendlyName 
      cfg.CreateMap<UxEntry<bool>, Entry<bool>>() 
       .ForMember(dest => dest.FriendlyName, opt => opt.UseValue("Title")); 

      cfg.CreateMap<CallScheduleProfile, CallScheduleProfileViewModel>(); 
     }); 

现在我们可以从CallScheduleProfileViewModel的构造函数中删除多余的属性初始化。

没有其他的变化运行你的代码将产生以下输出:

true  
Title 
+0

我居然发现'CFG。CreateMap ()。ForMember(dest => dest.Title,o => o.UseDestinationValue());'也工作 – Jon

+0

@Jon Wow,那很好... – Fabjan