Automapper Flattening Common Nested Relationship

235 views
Skip to first unread message

duyguse...@gmail.com

unread,
May 11, 2018, 6:25:28 AM5/11/18
to AutoMapper-users
I'm trying to use Automapper to flatten a Entityframework object that has a nested complex property to a few various models that all inherit the same common properties from a base class, a simplified version of this is as follows:
public class EFObject {
   
public int Id { get; set; }
   
public int NestedId { get; set; }
   
public virtual AnotherModel AnotherModel { get; set; }
}

public class AModel : Model {
   
public int AModelId { get; set; }
}

public class BModel : Model {
   
public int BModelId { get; set; }
}

As both AModel and BModel share a common base (Model) ideally I would like to declare a common map like so:
mapper.Map<AnotherModel, Model>();
And then when mapping EFObject to AModel I would map the AModelId property within
mapper.Map<EFObject, AModel>();

and then include the AnotherModel -> Model map so that I wouldn't have to map the common properties multiple times (once for AModel and again for BModel, etc).

I was able to achieve the above by using an AfterMap, i.e.

CreateMap<EFObject, AModel>()
   .AfterMap((src, dest) => Mapper.Map(src.AnotherModel, dest))
   .ReverseMap();


However there is a fairly major issue with this solution in that it relies on the static instance of Automapper, and as I am dependency injecting an instance of Automapper, my unit tests that use this map are all failing due to the static Mapper not being instantiated.

I could get around this problem by initializing the static instance in my unit test, but as it requires knowledge of how your maps are structured, it defeats the aim of using Automapper (I feel).

I also know that I could write a converter for each Model, however that isn't ideal as it produces a lot of additional code for something I feel is supported but I'm struggling to find the answer for.

Any ideas on the best way to structure my maps to get around this problem?


ushenko...@gmail.com

unread,
Jun 19, 2018, 2:41:34 AM6/19/18
to AutoMapper-users
Hi there!
I dont know what version of amutomapper you use, but with thee latest version AfterMap method has an overload with three params. The last one is of ResolutionContext type. There you can find Mapper property.
Reply all
Reply to author
Forward
0 new messages