Search code examples
c#automappereventhandler

Ignore mapping an event with Automapper


I have to two same objects (A , B). I want map all of A properties to B properties but i want ignore PropertyChanged event while mapping.

The signature of PropertyChanged is:

public event PropertyChangedEventHandler PropertyChanged;

My B object has some values in PropertyChanged befor mapping but the following code cause: B.PropertyChanged == Null:

B = Mapper.Map<myClass, myClass>(A);

I tried this one:

Mapper.CreateMap<myClass, myClass>().ForMember(x => x.PropertyChanged, opt => opt.Ignore())

But i get this error:

... PropertyChanged can only appear on the left hand side of += or -= ...

How can i ignore mapping an event handler property with Automapper???


Solution

  • You're using the wrong mapping statement.

    B = Mapper.Map<myClass, myClass>(A);
    

    creates a new B object. The previous object is gone. Obviously the new B doesn't have an event handler.

    Instead you should use

    Mapper.Map(A, B);
    

    Now the existing B receives A's values and you'll see that B's PropertyChanged event(s) will fire.