Beispiel #1
0
        internal ReMapper BuildMapping()
        {
            var mappedList = new List <MappedProperty <TSource, TResult> >();

            foreach (var property in _propertyList)
            {
                PropertyInfo sourceProperty = null;
                PropertyInfo targetProperty = null;

                if (property.SourceExpression != null)
                {
                    sourceProperty = ExpressionHelper.GetPropertyFromExpression(property.SourceExpression);
                }
                else if (!string.IsNullOrEmpty(property.SourcePropertyName))
                {
                    sourceProperty = typeof(TSource).GetProperty(property.SourcePropertyName);
                }

                if (sourceProperty == null && property.MappingFunc == null)
                {
                    throw new ArgumentNullException(nameof(sourceProperty));
                }

                if (property.TargetExpression != null)
                {
                    targetProperty = ExpressionHelper.GetPropertyFromExpression(property.TargetExpression);
                }
                else if (!string.IsNullOrEmpty(property.TargetPropertyName))
                {
                    targetProperty = typeof(TResult).GetProperty(property.TargetPropertyName);
                }
                else
                {
                    targetProperty = typeof(TResult).GetProperty(property.SourcePropertyName);
                }

                if (targetProperty == null)
                {
                    continue;
                }

                if (property.MappingFunc == null && sourceProperty?.PropertyType != targetProperty.PropertyType)
                {
                    var res = _reMapper.CanConvert(sourceProperty?.PropertyType, targetProperty.PropertyType);

                    if (res)
                    {
                        property.MappingFunc =
                            _reMapper.GetConverterExpression(sourceProperty?.PropertyType, targetProperty.PropertyType);
                    }
                }

                var mappedProperty = new MappedProperty <TSource, TResult>
                {
                    SourceProperty = sourceProperty,
                    TargetProperty = targetProperty,
                    MappingFunc    = property.MappingFunc
                };

                mappedList.Add(mappedProperty);
            }

            var converter = ExpressionHelper.BuildMapAction <TSource, TResult>(mappedList);

            _reMapper.AddToMappers((typeof(TSource), typeof(TResult)), converter);

            BuildGenerators <TSource>();
            BuildGenerators <TResult>();

            BuildConvertersForGenerics();

            return(_reMapper);
        }