我使用AutoMapper与EF& Web API 2.命令
tempValue = Mapper.Map<MwbePaymentMethodDtoInOut>(res);
似乎行不通。结果对象应该是没有Payments元素的对象,因为它被AutoMapper定义忽略(行:.ForSourceMember(src =&gt; src.Payments,opt =&gt; opt.Ignore()))。
Global.asax中
Namespace MobileWallet.Api
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
StartAutomapper();
}
private void StartAutomapper(){
Mapper.Initialize(cfg =>
{
AutoMapperConfiguration.Configure();
});
}
}
}
AutoMapper定义
public class MwbeToDomain : Profile
{
public override string ProfileName
{
get
{
return "MwbeToDomainMapping";
}
}
protected override void Configure()
{
CreateMap<MwbePaymentMethod, MwbePaymentMethodDtoInOut>()
.ForMember(dest => dest.methodType, opt => opt.ResolveUsing<EnumToStringResolver<MwbePaymentMethod.MethodTypeEnum>>().FromMember(source => source.MethodType))
.ForMember(dest => dest.BillingAddress, opt => opt.MapFrom(source => source.BillingAddress))
.ForSourceMember(source => source.UserData, opt => opt.Ignore())
.ForMember(dest => dest.expirationdate, opt => opt.ResolveUsing<DateTimeToString>().FromMember(source => source.ExpirationDate))
.ForSourceMember(src => src.Payments, opt => opt.Ignore())
.ForSourceMember(src => src.Number, opt => opt.Ignore());
}
}
我的代码出了什么问题?
增加:
我在设置配置后立即添加了AutoMapper验证:
private void StartAutomapper(){
//Mapper.AssertConfigurationIsValid();
Mapper.Initialize(cfg =>
{
AutoMapperConfiguration.Configure();
});
Mapper.AssertConfigurationIsValid();
}
验证码由app启动,但不会显示错误。
答案 0 :(得分:0)
首先尝试添加Mapper.AssertConfigurationIsValid();
答案 1 :(得分:0)
我可能没有正确阅读,但我不确定AutoMapperConfiguration是什么。由于您正在创建配置文件,我认为您需要告诉AutoMapper它,因此它知道使用它。尝试将StartAutomapper功能更改为以下内容:
private void StartAutomapper()
{
Mapper.Initialize(cfg =>
{
cfg.AddProfile<MwbeToDomain>();
});
Mapper.AssertConfigurationIsValid();
}
此外,在Profile的Configure方法中放置一个断点可能会有所帮助,以确保它被调用。
答案 2 :(得分:0)
我找到了解决方案,我的&#34;愚蠢&#34;错误:)。
我必须从目标类中删除被忽略的属性。当属性存在时,AutoMapper不会忽略它。