首页 > 解决方案 > 如果字符串不为空,则条件映射(ASP.NET Core)

问题描述

我在我的项目中使用 Automapper

在映射器中,我将字符串映射到ICollection.

这是我的做法

.ForMember(x => x.PropertyImages,
                opt => opt.MapFrom(aa => aa.Attachments.Split(';', StringSplitOptions.None).ToList()));

但是如果字符串为空。我有错误

对象未设置为对象的实例

仅当字符串不为空时,我如何进行条件映射

标签: c#asp.netasp.net-coreautomapper

解决方案


您可以使用三元运算符来检查字符串


.ForMember(x => x.PropertyImages,
      opt => opt.MapFrom(aa => !string.IsNullOrEmpty(aa.Attachments) ? aa.Attachments.Split(';', StringSplitOptions.None).ToList() : new List<string>()));

推荐阅读