我有下面的代码已经在Automapper的v3中工作,但不再在v5中。 更新它也适用于v4。Automapper v5升级后的空属性值
CallScheduleProfile
在其构造函数中将Title
属性设置为类的实例,该实例将值true
传递给它。
CallScheduleProfileViewModel
在其构造设置一个Title
属性到该传递的true
和"Title"
的值的不同的类的实例。
我已经在AutoMapper中为所有4个类设置了映射,然后我调用Map。
的结果是,该地图后Title
财产上CallScheduleProfileViewModel
有true
一个布尔值,但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; }
}
我居然发现'CFG。CreateMap()。ForMember(dest => dest.Title,o => o.UseDestinationValue());'也工作 –
Jon
@Jon Wow,那很好... – Fabjan