簡體   English   中英

如何配置Automapper 4以允許空目標值

[英]How can I configure Automapper 4 to allow a null destination value

我在解決如何使Automapper 4.2.1允許類型映射時遇到一些問題,其中目標值可能為null,具體取決於源值。

較舊版本的Automapper允許通過Mapper配置設置AllowNullDestination標志,但是我找不到新版本的等效配方,並且通過靜態Mapper對象配置的舊機制似乎已經過時。

我試過以下沒有成功:

  • Mapper.Configuration.AllowNullDestinationValues = true;
  • Mapper.AllowNullDestinationValues = true;
  • Mapper.Initialize(C => c.AllowNullDestinationValues = TRUE);

這是一個簡單的測試案例,展示了這個問題。 由於Substitute方法返回null,因此在AutoMapperMappingException的最后一行失敗。 我希望兩個映射都能成功。

我寧願避免在解決方案中使用.ForMember ,因為在我試圖解決的真實場景中,bool和'object'(實際上是一個自定義類)之間的映射應該應用於整個對象樹。

雖然StackOverflow上有幾個類似的問題,但我還沒有找到一個引用最新版Automapper的問題。

在此先感謝您的任何建議

using AutoMapper;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AutoMapperTest
{
    [TestClass]
    public class ExampleTest
    {
        [TestMethod]
        public void NullDestinationCanBeMapped()
        {
            var mapper = new MapperConfiguration(configuration =>
            {
                configuration.CreateMap<Source, Target>();
                //How should the following mapping be modified to pass the test?   
                configuration.CreateMap<bool, object>()
                .Substitute(i => i ? null : new object());
            }).CreateMapper();

            var target1 = mapper.Map<Source, Target>(new Source {Member = false}); //succeeds
            Assert.IsNotNull(target1.Member); //pass
            var target2 = mapper.Map<Source, Target>(new Source {Member = true}); //fails to map with exception
            Assert.IsNull(target2.Member); //not reached
        }
    }

    public class Source
    {
        public bool Member { get; set; }
    }

    public class Target
    {
        public object Member { get; set; }
    }
}

而不是使用替換 ,使用ConvertUsing ...

     configuration.CreateMap<bool, MyClass>()
     .ConvertUsing(i => i ? null : new object());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM