AutoMapper.Map忽略来自源对象中的所有空值的属性 [英] AutoMapper.Map ignore all Null value properties from source object

查看:6141
本文介绍了AutoMapper.Map忽略来自源对象中的所有空值的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图映射相同类型的两个对象。 我想要做的就是AutoMapper到igonore所有属性,有值的源对象中,并保持在目标对象的现有值。

I'm trying to map 2 objects of the same type. What I want to do is AutoMapper to igonore all the properties, that have Null value in the source object, and keep the existing value in the destination object.

我在我的资源库采用这种尝试,但它似乎并没有工作。

I've tried using this in my "Repository", but it doesn't seem to work.

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

可能是什么问题?

What might be the problem ?

推荐答案

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

Interesting, but your original attempt should be the way to go. Below test is green:

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

这篇关于AutoMapper.Map忽略来自源对象中的所有空值的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆