我在 RegisterMappings()
中定义了以下映射的 AutoMapperConfig
:
AutoMapper.Mapper.CreateMap<Member, PhotoViewModel>()
.ForMember(dest => dest.Show, opt => opt.MapFrom(src => src.ShowPhoto))
.ForMember(dest => dest.Value, opt => opt.MapFrom(src => AutoMapper.Mapper.Map<PhotoValueViewModel>(src));
AutoMapper.Mapper.CreateMap<Member, PhotoValueViewModel>();
此映射映射了 PhotoViewModel
的两个属性.首先它映射 Show
基于 src.ShowPhoto
的属性(property), 然后它映射一个 PhotoValueViewModel
进入Value
属性(property)。
映射有效!不幸的是,我有很多对象需要类似的映射。因此,我尝试将一些实现抽象为 AutoMapperExtension 方法。该方法如下所示:
public static IMappingExpression<TSource, TDestination> ApplyPropertyMapping<TSource, TDestination>
(this IMappingExpression<TSource, TDestination> iMappingExpression, Expression<Func<TSource, bool?>> show, Expression<Func<TSource, object>> value)
where TDestination : PropertyViewModel
{
iMappingExpression
.ForMember(dest => dest.Show, opt => opt.MapFrom(show))
.ForMember(dest => dest.Value, opt => opt.MapFrom(value));
return iMappingExpression;
}
我希望这个扩展方法允许我将原始映射定义为:
AutoMapper.Mapper.CreateMap<Member, PhotoViewModel>()
.ApplyPropertyMapping(src => src.ShowPhoto, src => AutoMapper.Mapper.Map<PhotoValueViewModel>(src));
但是没用!现在调用 Mapper.Map<Member, PhotoViewModel>(MemberObject, PhotoViewModelObject)
设置 PhotoViewModelObject.Value
属性为空。
造成差异的原因是什么?
其中一些对象的定义是:
public class Member
{
/**Irrelevant Properties Not Shown**/
public Guid? PhotoID { get; set; }
public string PhotoFileName { get; set; }
public bool? ShowPhoto { get; set; }
}
public class PropertyViewModel
{
public object Value { get; set; }
public bool? Show { get; set; }
}
public class PhotoViewModel : PropertyViewModel
{
public PhotoValueViewModel Value { get; set; }
}
public class PhotoValueViewModel
{
public Guid? PhotoID { get; set; }
public string PhotoFileName { get; set; }
public string PhotoUrl {get {return Utils.GeneratePhotoUrl(PhotoID); } }
}
最佳答案
PhotoViewModel
类包含两个名称为 Value
的属性, 其中之一在 PropertyViewModel
中定义类型为 object
.另一个定义在 PhotoViewModel
中。类型为 PhotoValueViewModel
(这基本上是 hiding 另一个属性,您应该从 Visual Studio 收到关于此的警告)。
在您的扩展方法中,您引用了 PropertyViewModel.Value
这是类型 object
这是因为 TDestination
此方法中声明类型可从 PropertyViewModel
分配(通过 where TDestination : PropertyViewModel
)。
您的扩展方法工作正常,它正在更改该属性的值 ( PropertyViewModel.Value
)。
您的原始映射(没有扩展方法)将值映射到 PhotoViewModel.Value
这是类型 PhotoValueViewModel
.
您可以使用 Visual Studio 调试器同时查看 PropertyViewModel.Value
和 PhotoViewModel.Value
在这两种情况下(有或没有扩展方法)。
关于c# - 为什么 AutoMapperExtension 的行为与直接实现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32915518/