简体   繁体   中英

C# Automapper Ignore Property When Null

I am creating an Automapper mapping between my AccountEditViewModel (View Model used for editing a user) and my User (Data Model representing a User in the database). If the password field is filled in, I want to encrypt that password and store it however if it is null in the I want to keep the old password. I have tried the code below however it is wrong, model.Ignore() doesn't return a string value. What is the best way of going about this. Can I accomplish this using the ForMember() method or do I need a custom resolver?

Mapper.CreateMap<AccountEditViewModel, User>()
                .ForMember(model => model.Password, model => model.MapFrom(user => user.Password != null ? EncryptPassword(user.Password) : model.Ignore()));

Try this:

Mapper.CreateMap<AccountEditViewModel, User>()
.ForMember(model => model.Password, model => model.Ignore()) 
.AfterMap((src, dst) =>
                    {
                        if (src.Password != null)
                            dst.Password= EncryptPassword(src.Password);

                    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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