Question

I want a generic update method which copies all properties of sourceObject to targetObject but not methods mentioned in exceptions.

Was it helpful?

Solution

Have you tried using AutoMapper? It allows you to define custom mapping as well as auto mapping.

--edit--

Example:

Given following types:

public class Type1
{
    public int MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }
    public int MyProperty3 { get; set; }
    public int MyProperty4 { get; set; }
    public int MyProperty5 { get; set; }
}

public class Type2
{
    public int MyProperty1 { get; set; }
    public int MyProperty2 { get; set; }
    public int MyProperty3 { get; set; }
    public int MyProperty7 { get; set; }
    public int MyProperty8 { get; set; }
}

To create a map which ignores 2 properties (MyProperty7 & MyProperty8):

var map = Mapper.CreateMap<Type1, Type2>().
            ForMember(dest => dest.MyProperty7, opt => opt.Ignore()).
            ForMember(dest => dest.MyProperty8, opt => opt.Ignore());

Finally copy:

Type2 type2Variable = Mapper.Map<Type1, Type2>(type1Variable);

--edit2--

Mapping same types example:

var map = Mapper.CreateMap<Type1, Type1>().
            ForMember(dest => dest.MyProperty4, opt => opt.Ignore()).
            ForMember(dest => dest.MyProperty5, opt => opt.Ignore());

use:

Type1 anotherType1Variable = Mapper.Map<Type1, Type1>(type1Variable);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top