我正在尝试使用
Automapper
来映射这些属性
public class SourceClass
{
public object emailNotification { get; set; }
}
public class DestinationClass
{
public int emailNotificationId { get; set; }
public string emailNotificationLookupName { get; set; }
}
当我调试它时,
emailNotification
= ValueKind = Object : "{ "id": 3, "lookupName": "Send Email Notification" }"
。
预期结果是
这是我当前的映射代码,但我有这个编译错误:
An expression tree may not contain an 'is' pattern-matching operator.
in src.emailNotification is JObject jObject
public class SourceProfile : AutoMapper.Profile
{
public SourceProfile()
{
CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.emailNotificationId, opt => opt.MapFrom(src =>
src.emailNotification != null && src.emailNotification is JObject jObject ? jObject["id"].Value<int>() : 0))
.ForMember(dest => dest.emailNotificationLookupName, opt => opt.MapFrom(src =>
src.emailNotification != null && src.emailNotification is JObject jObject ? jObject["lookupName"].Value<string>() : null))
;
}
}
您可以使用
as
运算符替换 is
来解决问题
CreateMap<SourceClass, DestinationClass>()
.ForMember(dest => dest.emailNotificationId, opt => opt.MapFrom(src =>
src.emailNotification != null && (src.emailNotification as JObject) != null ? (src.emailNotification as JObject)["id"].Value<int>() : 0))
.ForMember(dest => dest.emailNotificationLookupName, opt => opt.MapFrom(src =>
src.emailNotification != null && (src.emailNotification as JObject) != null ? (src.emailNotification as JObject)["lookupName"].Value<string>() : null))
由于验证
emailNotification
的逻辑不是 null
并且必须在多个位置重复 JObject
,因此您可以考虑迁移 AfterMap
操作中的逻辑:
CreateMap<SourceClass, DestinationClass>()
.AfterMap((src, dest, context) =>
{
if (src.emailNotification != null && src.emailNotification is JObject jObject)
{
dest.emailNotificationId = jObject["id"].Value<int>();
dest.emailNotificationLookupName = jObject["lookupName"].Value<string>();
}
});