AutoMapper在源属性的情况下将目标设置为null [英] AutoMapper set destination to null on condition of source property

查看:135
本文介绍了AutoMapper在源属性的情况下将目标设置为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在两个对象之间进行映射,并且根据源的条件,我希望目标为空.

I'm mapping between two objects and based on a condition of the source I would like the destination to be null.

例如,以下是这些类:

public class Foo
{
    public int Code { get; set; }
    public string Name { get; set; }

}

public class Bar
{
    public string Name { get; set; }
    public string Type { get; set; }
}

我的地图:

Mapper.CreateMap<Foo, Bar>()
            .AfterMap((s, d) => { if (s.Code != 0) d = null; });

但是它似乎忽略了AfterMap.尽管具有所有默认属性,但Bar已初始化.

But it seems to ignore the AfterMap. Bar is initialised although with all default properties.

如何基于不等于0的Code来使映射器返回null?

How can I get the mapper to return null based on Code not being equal to 0?

谢谢

推荐答案

一种可能的方法是-

class Converter : TypeConverter<Foo, Bar>
{
    protected override Bar ConvertCore(Foo source)
    {
        if (source.Code != 0)
            return null;
        return new Bar();
    }
}


static void Main(string[] args)
    {
        Mapper.CreateMap<Foo, Bar>()
            .ConvertUsing<Converter>();


        var bar = Mapper.Map<Bar>(new Foo
        {
            Code = 1
        });
        //bar == null true
    }

这篇关于AutoMapper在源属性的情况下将目标设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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