Mapping to existing object of same type returns the source instead of modifying the destination
See original GitHub issueEDIT: actually, the problem is not related to CreateMissingTypeMaps
; see comments below
Just noticed a bug where CreateMissingTypeMaps = true
has no effect when you pass an existing destination object to Mapper.Map
. Here’s a quick repro using LinqPad:
void Main()
{
var foo1 = new Foo { X = 42, Y = 123, Bar = new Bar { Z = 999 } };
var foo2 = new Foo();
var foo3 = Mapper.Map<Foo, Foo>(foo1, foo2, o => o.CreateMissingTypeMaps = true);
Console.WriteLine ("foo3 == foo1: {0}", foo3 == foo1); // true; expected false
Console.WriteLine ("foo3 == foo2: {0}", foo3 == foo2); // false; expected true
Console.WriteLine (foo2.ToString()); // Foo(X = 0, Y = 0, Bar = ); expected Foo(X = 42, Y = 123, Bar = Bar(Z = 999))
}
class Foo
{
public int X { get; set; }
public int Y { get; set; }
public Bar Bar { get; set; }
public override string ToString() { return string.Format("Foo(X = {0}, Y = {1}, Bar = {2})", X, Y, Bar); }
}
class Bar
{
public int Z { get; set; }
public override string ToString() { return string.Format("Bar(Z = {0})", Z); }
}
Mapping to a new instance with Mapper.Map<Foo>(foo1)
works as expected.
Also, if I explicitly create the map for Foo -> Foo
, then the map for Bar -> Bar
is correctly created, so it seems the problem only affects the root of the mapping.
Another issue (perhaps unrelated) that bothers me is that the mapping fails silently… the destination object is left untouched, and Mapper.Map
just returns the source object (it returns the destination object when the mapping succeeds). Shouldn’t it throw an exception?
Issue Analytics
- State:
- Created 9 years ago
- Reactions:1
- Comments:8 (6 by maintainers)
Top GitHub Comments
OK, I think I know what’s going on; if there is no map defined for
Foo -> Foo
, AutoMapper usesAssignableMapper
, which just returns the source value. But in the case of a mapping with destination, it doesn’t make sense: I explicitly want to copy the source object’s properties to the destination object…Ok, so to use map to auto-assign same properties on destination object of type A from source type A, I can create a profile :
But imagine that I want to be able to use this on my 100 classes likewise. I’ll get something like :
Is there another “state of the Automapper art” way of doing it ? For instance in the
.Map(source, destination, ????)
call directly ? (my goal is to prevent silent logical errors if I forget to add the dummy <X, X> profile for my 99th class X)