简体   繁体   English

ConvertUsing之后忽略未映射的成员

[英]Ignoring unmapped members after ConvertUsing

this is my code : 这是我的代码:

public class UserProfile:Profile
{
    public UserProfile()
    {
        CreateMap<UserViewModel, ApplicationUsers>().ConvertUsing<UserEncryptor>();
    }

}
public class UserEncryptor : ITypeConverter<UserViewModel, ApplicationUsers>
{
    private readonly IConfigurationRoot _configuration;
    public UserEncryptor(IConfigurationRoot configuration)
    {
        _configuration = configuration;
    }

    public ApplicationUsers Convert(UserViewModel source, ApplicationUsers destination, ResolutionContext context)
    {
        if (context==null||source == null) return null;
        var aes = new Common.EncryptionAes(_configuration[key: "Keys:AesKey"]);
        return new ApplicationUsers
        {
            UserName = aes.EncryptAes(source.Username),
            Email = aes.EncryptAes(source.Email),
            PhoneNumber = aes.EncryptAes(source.MobileNumber),
            User = new User
            {
                FirstName = aes.EncryptAes(source.FirstName),
                LastName = aes.EncryptAes(source.LastName),
                Gender = aes.EncryptAes(source.Gender.ToString()),
                ProfileImage = aes.EncryptAes(source.ProfileImage.FileName)
            }
        };
    }
}

Note that ApplicationUsers is inherited from IdentityUser Class. 请注意,ApplicationUsers继承自IdentityUser类。

When I tested this mapping,I got this error : 当我测试此映射时,出现此错误:

System.NullReferenceException: Object reference not set to an instance of an object. System.NullReferenceException:对象引用未设置为对象的实例。

I know this error is for that some members are not ignored. 我知道此错误是因为某些成员未被忽略。 Something like this 像这样

 CreateMap<UserViewModel ,ApplicationUsers >()
.ConvertUsing(converter=> new ApplicationUsers(){
Email = converter.Email,
....
});

will help me because by default ignore rest of the members but the problem is that if I want to use this kind of code, I cant encrypt my members because I don't access to DI configuration for profile.Because profile is parameter less. 会帮助我,因为默认情况下会忽略其余成员,但是问题是,如果我想使用这种代码,由于无法访问profile的DI配置,因此无法加密成员。因为profile的参数较少。

I need something similar to upper code that can implement in ITypeConverter functions. 我需要类似于可以在ITypeConverter函数中实现的上层代码的内容。

Anyone has any solution ? 任何人有什么解决方案吗?

refer to this link GitHub Issue 请参阅此链接GitHub问题

that I asked my self,I got my answer : 我问自己,我得到了答案:

In my test I must define the profile like this : 在我的测试中,我必须像这样定义配置文件:

 services.AddAutoMapper(typeof(UserProfile));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM