如何在AutoMapper中配置条件映射? [英] How to configure Conditional Mapping in AutoMapper?

查看:245
本文介绍了如何在AutoMapper中配置条件映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下实体(类)

Suppose I have the following entities (classes)

public class Target
{
    public string Value;
}


public class Source
{
    public string Value1;
    public string Value2;
}

现在,我想配置自动映射,如果Value1以"A"开头,则将Value1映射到Value,否则,我想将Value2映射到Value.

Now I want to configure Auto Map, to Map Value1 to Value if Value1 starts with "A", but otherwise I want to map Value2 to Value.

这是我到目前为止所拥有的:

This is what I have so far:

Mapper
    .CreateMap<Source,Target>()
    .ForMember(t => t.Value, 
        o => 
            {
                o.Condition(s => 
                    s.Value1.StartsWith("A"));
                o.MapFrom(s => s.Value1);
                  <<***But then how do I supply the negative clause!?***>>
            })

然而,还有更难理解的部分是如何告诉AutoMapper如果较早的条件失败了,请接受s.Value2 .

However the part the still eludes me is how to tell AutoMapper to go take s.Value2 should the earlier condition fails.

在我看来,API的设计不尽如人意……但这可能是因为我缺乏知识.

It just seems to me the API was not designed as well as it could be... but may be it's my lack of knowledge getting in the way.

推荐答案

尝试一下

 Mapper.CreateMap<Source, Target>()
        .ForMember(dest => dest.Value, 
                   opt => opt.MapFrom
                   (src => src.Value1.StartsWith("A") ? src.Value1 : src.Value2));

Condition选项用于向映射该属性之前必须满足的属性添加条件,而MapFrom选项用于执行自定义源/目标成员映射.

Condition option is used to add conditions to properties that must be met before that property will be mapped and MapFrom option is used to perform custom source/destination member mappings.

这篇关于如何在AutoMapper中配置条件映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆