Search code examples
c#entity-framework-6automapper-5

How to use CreateMissingTypeMaps option and manual mappings with EF Proxy Classes?


I have a situation that requires to use CreateMissingTypeMaps and manual mappings at the "same time" (or at least at the same configuration).

Scenario: The Domain and View Model classes are manually mapped using profiles. The CreateMissingTypeMaps property is necessary because I have an anticorruption layer to access a legacy system which returns anonymous objects.

The issue is that the manual mapping has it's mapping overhidden by CreateMissingTypeMaps option when it is set to true and I can't map anonymous objects when it is false.

I tried to set CreateMissingTypeMaps inside the MapperConfiguration, inside a profile and also inside a profile with a mapping condition but all of them failed.

The code below is my attempt to do a conditional profile that should be applied just for anonymous objects.

    public class AnonymousProfile : Profile
    {
        public AnonymousProfile()
        {
            AddConditionalObjectMapper().Where((s, d) => s.GetType().IsAnonymousType());
            CreateMissingTypeMaps = true;
        }
    }

   // inside my MapperConfiguration
   cfg.AddProfile(new AnonymousProfile()); // also tried cfg.CreateMissingTypeMaps = true;

[EDIT:] The original question didn't mention EF but I discovered that its proxy classes are part of the problem.


Solution

  • I refactored my code following these directions pointed by Tyler on Github.

    1. My anonymous type check had a bug (I should not use GetType)
    2. Objects from System.Data.Entity.DynamicProxies have to be ignored

    My rewritten AnonymousProfile class:

    public class AnonymousProfile : Profile
    {
        public AnonymousProfile()
        {
            AddConditionalObjectMapper().Where((s, d) => 
                s.IsAnonymousType() && s.Namespace != "System.Data.Entity.DynamicProxies");
        }
    }