V
V
Vadim Ivanenko2015-01-21 14:17:37
.NET
Vadim Ivanenko, 2015-01-21 14:17:37

automapper. How to make it ignore properties in Destination for which there is no match in Source?

There are classes BLL.Story (fewer properties) and DAL.Story (more properties).
When converting from DAL.Story to BLL.Story everything works. If you perform the reverse operation, then an exception is thrown:
{"Missing type map configuration or unsupported mapping.
Mapping types: RuntimeType -> Type System.RuntimeType -> AgilityTracker.DAL.Type
Destination path: Story.Type.Type
Source value: AgilityTracker.BLL .DataModel.Story"}
I assume that the mapper does not know how to fill in the fields in the Destination, which are not in the Source.
How to set up a mapper so that in such cases these fields are filled with default values ​​that are defined for their types, respectively?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim Ivanenko, 2015-01-21
@supra7sky

Decision:

using System.Linq;
using System.Reflection;
using AutoMapper;

namespace AgilityTracker.BLL.Extension
{
    public static class MappingExpressionExtension
    {
        /// <summary>
        /// Игнорирует свойства в Destination для которых нет соотвествия в Source
        /// </summary>
        public static IMappingExpression<TSource, TDest> IgnoreAllUnmapped<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
        {
            var destinationProperties = typeof(TDest).GetProperties().Select<PropertyInfo, string>(s => s.Name);
            var sourceProperties = typeof(TSource).GetProperties().Select<PropertyInfo, string>(s => s.Name);
            var difference = destinationProperties.Except(sourceProperties);
            difference.Each(item => expression.ForMember(item, o => o.Ignore()));
            return expression;
        }
    }
}

Usage:
using AgilityTracker.BLL.Extension;
...
Mapper.CreateMap<Story, DAL.Story>()
                .IgnoreAllUnmapped();

There is no standard method, as I understand it, in AutoMapper?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question