AutoMapper.Map はソースオブジェクトのすべての Null 値プロパティを無視します 質問する

AutoMapper.Map はソースオブジェクトのすべての Null 値プロパティを無視します 質問する

Null同じタイプの 2 つのオブジェクトをマップしようとしています。AutoMapper で、ソース オブジェクトに値があるすべてのプロパティを無視し、宛先オブジェクトの既存の値を保持するようにしたいです。

これを「リポジトリ」で使用してみましたが、動作しないようです。

Mapper.CreateMap<TEntity, TEntity>().ForAllMembers(p => p.Condition(c => !c.IsSourceValueNull));

何が問題なのでしょうか?

ベストアンサー1

興味深いですが、最初の試みをそのまま実行する必要があります。以下のテストは緑色です。

using AutoMapper;
using NUnit.Framework;

namespace Tests.UI
{
    [TestFixture]
    class AutomapperTests
    {

      public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public int? Foo { get; set; }
        }

        [Test]
        public void TestNullIgnore()
        {
            Mapper.CreateMap<Person, Person>()
                    .ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));

            var sourcePerson = new Person
            {
                FirstName = "Bill",
                LastName = "Gates",
                Foo = null
            };
            var destinationPerson = new Person
            {
                FirstName = "",
                LastName = "",
                Foo = 1
            };
            Mapper.Map(sourcePerson, destinationPerson);

            Assert.That(destinationPerson,Is.Not.Null);
            Assert.That(destinationPerson.Foo,Is.EqualTo(1));
        }
    }
}

おすすめ記事