AutoMapper.Map忽略源对象的所有Null值属性

Mar*_*rty 21 .net c# repository automapper

我正在尝试映射2个相同类型的对象.我想要做的是AutoMapper to toigonore所有属性,它们Null在源对象中有值,并保留目标对象中的现有值.

我已经尝试在我的"存储库"中使用它,但它似乎不起作用.

Mapper.CreateMap<TEntity, TEntity>().ForAllMembers(p => p.Condition(c => !c.IsSourceValueNull));
Run Code Online (Sandbox Code Playgroud)

可能是什么问题?

Voi*_*Ray 27

有趣,但你原来的尝试应该是要走的路.以下测试为绿色:

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于更高版本,答案是@nenad 是正确的方法。您还可以检查此答案:/sf/answers/3076341201/ (2认同)

Nen*_*nad 8

Condition带有 3 个参数的重载让您使表达式等效于您的示例p.Condition(c => !c.IsSourceValueNull)

方法签名:

void Condition(Func<TSource, TDestination, TMember, bool> condition
Run Code Online (Sandbox Code Playgroud)

等价表达式:

CreateMap<TSource, TDestination>.ForAllMembers(
    opt => opt.Condition((src, dest, sourceMember) => sourceMember != null));
Run Code Online (Sandbox Code Playgroud)