且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AutoMapper映射到可为空的属性的属性

更新时间:2022-04-30 08:39:10

您可以编写如下的映射代码:

You could write the mapping code like follows:

Mapper.CreateMap<Contact, ContactModel>()
            .ForMember( x => x.UserName,  opt => opt.MapFrom( y => (y.User != null) ? y.User.UserName : "" ) );

这将检查 User 是否为空,然后分配一个空字符串或 UserName .

This will check if the User is null or not and then assign either an emtpy string or the UserName.