1

I don't know why, at some point AutoMapper doesn't map source to a destination object.

   var result = Mapper.Map<User, User>(userToImport, userToUpdate);
   var areEquals = result == userToUpdate; //FALSE !!! Why?
   var areEquals2 = result.Equals(userToUpdate); //FALSE !!! Why?

userToUpdate is not updated with new values from userToImport. result is a correct resulting object of mapping. But result and userToUpdate are different objects.

The main problem is, why userToUpdate is not updated?

4
  • 2
    How are == and Equals implemented? Commented Apr 24, 2014 at 15:23
  • 1
    If you do not create the map first Mapper.CreateMap<User, User>(); the destination object will not be filled with the values of the source object, but the returning object will be filled. Also, you are comparing 2 different references and that will return false in this case. You need to override operator == or Equals function and do your comparison logic (this.prop1 == obj.prop1) Commented Apr 25, 2014 at 8:19
  • @leskovar Mapper.Map<,>() returns the SAME reference specified in the destination argument. So a comparison with either Equals or == will result in true if a map exists (See my answer). No overriding is needed, the problem lies in the missing CreateMap. Commented Apr 25, 2014 at 10:46
  • @Alex yes, exactly I have not called CreateMap. This was the cause why I've got such behavior. And it was weird for me. Commented Apr 25, 2014 at 11:49

2 Answers 2

5

You'll have to create a map first or else it won't update and return the object of the destination parameter.

 Mapper.CreateMap<User, User>();
Sign up to request clarification or add additional context in comments.

2 Comments

This actually turns out to be true. I'm a bit surprised that AM doesn't throw an exception when the mapping is not created.
I suspect you are right. Because it worked for me in the past. I will check and get back to you later. Thanks!
-2

You need to do something like this:

public class User
{
    public int Property1 { get; set; }
    public int Property2 { get; set; }

    public override bool Equals(object obj)
    {
        if (!(obj is User))
            return false;
        else
        {
            Usero = obj as User;
            return o.Property1 == this.Property1 && o.Property2 == this.Property2;
        }

    }
}

After that you can do obj1.Equals(obj2);

1 Comment

This has nothing to do with it. AutoMapper.Map(source,destination) returns the destination object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.