AutoMapper How To Map Object A To Object B Differently Depending On Context

后端 未结 3 1002
面向向阳花
面向向阳花 2020-12-24 09:16

Calling all AutoMapper gurus!

I\'d like to be able to map object A to object B differently depending on context at runtime. In particular, I\'d like to ignore certai

3条回答
  •  我在风中等你
    2020-12-24 09:49

    To me, it sounds like a better design might be to have multiple destination classes (possibly inheriting from a common base or implementing a common interface)

    If the unmapped properties will never be used in one of the variations, you could leave them out entirely (giving compile time guarantee that they aren't used by mistake), throw an exception when they are accessed (not as good as a compile time guarantee, but sometimes you need the full interface to be implemented) or even use a substitute value.

    For example:

    public class Source
    {
        public string Name {get;set;}
        public BigEntity {get;set;}
    
        /* other members */
    }
    
    public class SourceDTO
    {
        public string Name {get;set;}
        public BigEntity {get;set;}
    }
    
    public class SourceSummaryDTO
    {
        public string Name {get;set;}
    }
    

    Alternatively, you could do this:

    public class SourceSummaryDTO : SourceDTO
    {
        public string Name {get;set;}
        public BigEntity 
        {
            get{throw new NotSupportedException();}
            set{throw new NotSupportedException();}
        }
    }
    

    That way, you could pass a SourceSummaryDTO as if it was a SourceDTO.

    Having properties conditionally populated sounds like a recipe for trouble to me - I'd rather have classes that are explicit about what they contain, especially with Data Transfer objects.

    For me, the best thing about Automapper is the ability to verify the mappings and then know that every property on destination classes will be populated.

提交回复
热议问题