InvalidOperationException when mapping types used via .Include<>

29 views
Skip to first unread message

ccbr...@gmail.com

unread,
Jul 6, 2016, 10:30:53 AM7/6/16
to AutoMapper-users
I am having an issue  when using .Include<>. Here is an example:

[TestClass]
public class UnitTest1
{
static UnitTest1()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Base, Target>()
.Include<Derived, Target>();
});
}

[TestMethod]
public void TestMethod1()
{
var src = new Derived
{
X = 5
};

var dest = Mapper.Map<Derived, Target>(src);

Assert.AreEqual(src.X, dest.X);
}
}

class Base
{
public int X { get; set; }
}

class Derived : Base { }

class PolicyBase : Base { }

class Target
{
public int X { get; set; }
public string S { get; set; }
}

This mapping worked successfully from at least 3.3 until the 4.2.0 release.  Starting in 4.2.0 (and in 5.0.0), it gives the below exception:
Unable to create instance of class AutoMapperTest.UnitTest1. Error: System.InvalidOperationException: Missing map from Base to Target. Create using Mapper.CreateMap<BaseTarget>..
    at AutoMapper.QueryableExtensions.Impl.QueryMapperHelper.MissingMapException(Type sourceType, Type destinationType)
   at AutoMapper.MapperConfiguration.<GetDerivedTypeMaps>d__89.MoveNext()
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
   at AutoMapper.MapperConfiguration.Seal()
   at AutoMapper.MapperConfiguration..ctor(Action`1 configure, IEnumerable`1 mappers, IEnumerable`1 typeMapObjectMappers)
   at AutoMapperTest.UnitTest1..cctor() in C:\Development\TestApps\AutoMapperTest\AutoMapperTest\UnitTest1.cs:line 13

I also tested this using the non-static API, but didn't have any luck there either.

I can fix it by adding:

cfg.CreateMap<DerivedTarget>();

at initialization, but I thought the purpose of .Include<> was to avoid that.

Any help is much appreciated!

Thanks!
Chris Bristol

Jimmy Bogard

unread,
Jul 6, 2016, 10:40:02 AM7/6/16
to automapper-users
No, that's not the purpose of Include. The purpose is to combine configuration of two different type maps, and inherit base map configuration to the sub map. Looks like it was working accidentally before.

--
You received this message because you are subscribed to the Google Groups "AutoMapper-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to automapper-use...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

ccbr...@gmail.com

unread,
Jul 6, 2016, 10:41:42 AM7/6/16
to AutoMapper-users
I was afraid you were going to say that! :)

Jimmy Bogard

unread,
Jul 6, 2016, 10:57:05 AM7/6/16
to automapper-users
Yeah sorry :)
Reply all
Reply to author
Forward
0 new messages