How to copy all fields from one object to another, but only when destination value is NULL

时间:2015-04-23 05:21:23

标签: c# automapper

I'd like to merge one object into another in a generic way that can be used repeatedly for other more complex objects. I only want the NULLs to change.

ie. merge sourcePerson and detinationPerson to get resultingPerson (below)

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

var sourcePerson = new Person
{
    FirstName = "Bill",
    LastName = "Smith",
    Age = 43,
    Address = "123 Some Street"
};
var destinationPerson = new Person
{
    FirstName = "Barbara",
    LastName = null,
    Age = 41,
    Address = null
};
var resultingPerson = new Person
{
    FirstName = "Barbara",
    LastName = "Smith",
    Age = 41,
    Address = "123 Some Street"
};

I've tried Automapper, but can't seem to configure it properly. I feel like the following should work. Help?

Mapper.CreateMap<Person, Person>().ForAllMembers(opt => opt.UseDestinationValue());
Mapper.Map(sourcePerson, destinationPerson);

2 个答案:

答案 0 :(得分:1)

感谢IronGeek和tutok。

是的,以下工作:

Mapper.CreateMap<Person, Person>()
      .ForAllMembers(opt => opt.Condition(person => person.DestinationValue == null));

答案 1 :(得分:0)

你可以使用这样的反射:

   public static T Merge<T>(T source, T destination)
     {
         var returnvalue = (T) Activator.CreateInstance(typeof (T));
         foreach (var field in destination.GetType().GetProperties())
         {
             field.SetValue(returnvalue,
                 field.GetValue(destination, null) == null ? field.GetValue(source) : field.GetValue(destination));
         }
         return returnvalue;
     }

除了简单的DTO之外,我还没有测试过这个。