简体   繁体   English

C#Automapper忽略属性时为空

[英]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). 我正在我的AccountEditViewModel (用于编辑用户的View Model)和我的User (表示数据库中User数据模型)之间创建一个Automapper映射。 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. 我已经尝试了下面的代码,但它是错误的,model.Ignore()不返回字符串值。 What is the best way of going about this. 解决这个问题的最佳方式是什么? Can I accomplish this using the ForMember() method or do I need a custom resolver? 我可以使用ForMember()方法完成此操作还是需要自定义解析器?

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);

                    });

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

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