简体   繁体   English

自动映射 - 当源对象具有值的属性时,不映射

[英]Automapper - Don't map when a source object has a property with a value

Our entities have a field called "DateDeleted". 我们的实体有一个名为“DateDeleted”的字段。 At times we might have these loaded into entities and we want to filter them out before sending them to the client. 有时我们可能会将这些加载到实体中,我们希望在将它们发送到客户端之前将其过滤掉。

Our Entities also have child entities which have child entities, all who have a DateDeleted. 我们的实体也有子实体,其中包含子实体,所有子实体都有DateDeleted。

What's the best practice to implement this with Automapper - Specifically - how can I map a Null value to the destination (for the entire object) when the source has a Date Deleted property with a value? 使用Automapper实现此功能的最佳做法是什么 - 具体来说 - 当源具有带有值的Date Deleted属性时,如何将Null值映射到目标(对于整个对象)?

You can ignore a specific property when you configure your mappings 配置映射时,可以忽略特定属性

CreateMap<srcType, destType>.ForMember(x => x.DateDeleted, opt => opt.Ignore());

EDIT: To do custom conditional logic during the mapping you will need to implement a custom resolver: 编辑:要在映射期间执行自定义条件逻辑,您需要实现自定义解析器:

public class NullCheckResolver : IValueResolver<TSrc, TDest, TProp>
{
    public TProp Resolve(TSrc source, TDest destination, TProp member, ResolutionContext context)
    {
        if (member.DateDeleted == null)
            return member;
        return null;
    }
}

CreateMap<TSrc, TDest>().ForMember(dest => dest.MyOptionalProperty, opt => opt.ResolveUsing<NullCheckResolver>());

For more details on custom resolvers, see the AutoMapper documentation 有关自定义解析程序的更多详细信息,请参阅AutoMapper文档

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

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