簡體   English   中英

AutoMapper:如果指定類型的源對象為null,則將目標對象的所有屬性設置為默認值

[英]AutoMapper: Set all properties of destination object to default if source object is null for specified types

如果源對象對於指定的類為空,是否可以將AutoMapper配置為將所有屬性設置為默認值? 我知道我應該使用Mapper.AllowNullDestinationValues = false; 在應用程序中為所有類做我想做的事。 這里是我用於測試的采樣代碼,但它不起作用

public class A
{
    static A()
    {
        Mapper.Initialize(
            config =>
                {
                    config.ForSourceType<B>().AllowNullDestinationValues = false;
                    config.CreateMap<B, A>()
                        .ForMember(member => member.Name, opt => opt.Ignore());
                });
        //Mapper.AllowNullDestinationValues = false;

        Mapper.AssertConfigurationIsValid();
    }

    public void Init(B b)
    {
        Mapper.DynamicMap(b, this);
    }

    public int? Foo { get; set; }
    public double? Foo1 { get; set; }
    public bool Foo2 { get; set; }
    public string Name { get; set; }
}

public class B
{
    public string Name { get; set; }
    public int? Foo { get; set; }
    public double? Foo1 { get; set; }
    public bool Foo2 { get; set; }
}

使用此代碼:

var b = new B() {Foo = 1, Foo1 = 3.3, Foo2 = true, Name = "123"};
var a = new A {Name = "aName"};
a.Init(b);      // All ok: Name=aName, Foo=1, Foo1=3,3, Foo2=True
a.Init(null);   // Should be Name=aName, Foo=null, Foo1=null, Foo2=False, 
                // but a has the same values as on a previous line

它必須與已經映射的“a”相關。

var a = new A {Name = "aName"};
a.Init(b);
a.Init(null);

所有映射都被緩存,因此如果您嘗試重新映射相同的實例,則automapper將保留原始結果。

為了測試它,請嘗試:

        var c = new A {Name = "x"};
        c.Init(null); 

這是類似問題的鏈接

如果設置Mapper.Configuration.AllowNullDestinationValues = false它看起來會替換為null:

public class A
    {
        static A()
        {
            Mapper.Initialize(
                config =>
                {
                    config.ForSourceType<B>().AllowNullDestinationValues = false;
                    config.CreateMap<B, A>()
                        .ForMember(member => member.Name, opt => opt.Ignore());
                });
            Mapper.Configuration.AllowNullDestinationValues = false;

            Mapper.AssertConfigurationIsValid();
        }

        public void Init(B b)
        {
            Mapper.DynamicMap(b, this);
        }

        public int? Foo { get; set; }
        public double? Foo1 { get; set; }
        public bool Foo2 { get; set; }
        public string Name { get; set; }
    }

暫無
暫無

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

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