C#:AutoMapper 定义由 Web APi 2 - 集合元素未被忽略

C#: AutoMapper definition is working by Web APi 2 - collection element is not ignored

我在 EF 和 Web 中使用 AutoMapper API 2. 命令

tempValue = Mapper.Map<MwbePaymentMethodDtoInOut>(res);

好像不行。结果对象应该是没有 Payments 元素的对象,因为它被 AutoMapper 定义忽略(行:.ForSourceMember(src => src.Payments, opt => 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启动了验证码,没有报错

首先尝试添加 Mapper.AssertConfigurationIsValid();

AutoMapper: Configuration Validation

我可能没看对,但我不确定 AutoMapperConfiguration 是什么。由于您正在创建配置文件,我认为您需要将其告知 AutoMapper,以便它知道使用它。尝试将您的 StartAutomapper 函数更改为如下内容:

private void StartAutomapper()
{
    Mapper.Initialize(cfg =>
    {                
        cfg.AddProfile<MwbeToDomain>();
    });

    Mapper.AssertConfigurationIsValid();
}

另外,在 Profile 的 Configure 方法中放置一个断点以确保它被调用可能会有所帮助。

我找到了解决方案,我的 "stupid" 错误 :)。

我不得不从目标 class 中删除被忽略的 属性。当 属性 存在时,它不会被 AutoMapper 忽略。