c# - AutoMapper.Map 忽略源对象中的所有 Null 值属性

标签 c# .net repository automapper

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

我试过在我的“存储库”中使用它,但它似乎不起作用。

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

可能是什么问题?

最佳答案

有趣,但您最初的尝试应该是可行的方法。下面的测试是绿色的:

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));
        }
    }
}

关于c# - AutoMapper.Map 忽略源对象中的所有 Null 值属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12514084/

相关文章:

C# 为什么使用存储库作为属性?

ASP.NET MVC : How-to inform Model/View about changes in the repository?

c# - C#中用于存储库模型的实体基类设计

c# - 部分类调试

c# - PInvoke NetLocalGroupGetMembers 遇到 FatalExecutionEngineError

.net - 有谁知道在同一台机器上的应用程序之间进行本地消息传递的快速总线?

.net - 使用 jquery 调用 .net Web 服务的最佳方式是什么?

MVVM:删除一个 CustomerViewModel,但如何获取其中的 Customer 模型?

c# - C# 中的运算符 '=' 链接 - 这个测试肯定会通过吗?

c# - Unity 与 azure 语音 sdk