Example #1
0
        /// <summary>
        /// Resolves a mapping created from type TFrom to type TTo.
        /// </summary>
        /// <typeparam name="TTo">The requested mapping result</typeparam>
        /// <typeparam name="TFrom">The input type</typeparam>
        /// <param name="from">The input object, TFrom</param>
        /// <returns>A type TTo object, in case mapping was successful</returns>
        public TTo MapTo <TTo, TFrom>(TFrom from)
            where TTo : class
            where TFrom : class
        {
            var fromType = typeof(TFrom);
            var toType   = typeof(TTo);
            var key      = new MappingKey
            {
                From = fromType,
                To   = toType
            };

            if (!mappings.ContainsKey(key))
            {
                throw new NotSupportedException($"Mapping from {fromType.Name} to {toType.Name} not supported.");
            }

            var mapping = mappings[key];
            var mapped  = mapping(from);

            if (mapped == null)
            {
                throw new NotSupportedException($"Mapping resulted in null for {fromType.Name} to {toType.Name}.");
            }

            if (!(mapped is TTo))
            {
                throw new NotSupportedException($"Mapping resulted in not supported result for {fromType.Name} to {toType.Name}.");
            }

            return(mapped as TTo);
        }
Example #2
0
        /// <summary>
        /// Use this function to create a map from type A to type B
        /// </summary>
        /// <typeparam name="TFrom">Type A</typeparam>
        /// <typeparam name="TTo">Type B</typeparam>
        /// <param name="mapping">The actual mapping code</param>
        public Mapping <TFrom, TTo> CreateMap <TFrom, TTo>(Func <TFrom, Mapper, TTo> mapping) where TFrom : class
            where TTo : class
        {
            var fromType = typeof(TFrom);
            var toType   = typeof(TTo);
            var key      = new MappingKey
            {
                From = fromType,
                To   = toType
            };

            if (mappings.ContainsKey(key))
            {
                throw new NotSupportedException($"Mapping from {fromType.Name} to {toType.Name} already in registry.");
            }

            //func translation
            object mappingFunction(object a) => mapping(a as TFrom, this);

            mappings.Add(key, mappingFunction);

            return(new Mapping <TFrom, TTo>(mapping));
        }