【问题标题】:Automapper "IsNull" Destination postfix not working properlyAutomapper“IsNull”目标后缀无法正常工作
【发布时间】:2019-04-13 02:17:07
【问题描述】:

我有以下代码:

  class Program
{
    static void Main(string[] args)
    {
        var srcClass = new SourceClass { Value1 = null, Value2 = 10, Value3 = 20 };
        Mapper.Initialize(cfg =>
        {
            cfg.RecognizeDestinationPostfixes("IsNull");
            cfg.CreateMap<SourceClass, TargetClass>();
        });
        var targetClass = Mapper.Map<SourceClass, TargetClass>(srcClass);

    }
}
public class SourceClass
{
    public int? Value1 { get; set; }
    public int? Value2 { get; set; }
    public int? Value3 { get; set; }
}
public class TargetClass
{
    public bool Value1IsNull{ get; set; }
    public bool Value2IsNull { get; set; }
    public bool Value3IsNull { get; set; }
}

我希望 targetClass 实例具有以下值:true、false、false; 但我收到相反的结果:假,真,真。

如何解决这个问题?

【问题讨论】:

  • 您需要通过从 int 创建地图来告诉 AM 您想要什么?布尔值。

标签: c# .net mapping automapper


【解决方案1】:

这是因为当我们将整数转换为布尔值时,它会为 null 返回 false,为值返回 true。

            int? a;
            a = null;
            //Convert null to boolean
            bool a1 = Convert.ToBoolean(a);
            Console.WriteLine("Null Value - " + a1);
            a = 1;
            //Convert integer value to boolean
            a1 = Convert.ToBoolean(a);
            Console.WriteLine("Have Value - " + a1);
            var srcClass = new SourceClass { Value1 = null, Value2 = 1, Value3 = 20 };
            Mapper.Initialize(cfg =>
            {
                cfg.RecognizeDestinationPostfixes("IsNull");
                cfg.CreateMap<SourceClass, TargetClass>();
            });
            var targetClass = Mapper.Map<SourceClass, TargetClass>(srcClass);
            Console.WriteLine(targetClass.Value1IsNull+" - " +targetClass.Value2IsNull+" - " +targetClass.Value3IsNull);  

输出:

Null Value - False
Have Value - True
False - True - True

【讨论】:

    猜你喜欢
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 2012-11-12
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多