Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
namespace DovetailCRM.Core.Web.Mapping
{
public static class AutoMapperExtensions
{
public static void CreateMapsForSourceTypes(this IConfiguration configuration, Func<Type, bool> filter, Func<Type, Type> destinationType, Action<IMappingExpression, Type, Type> mappingConfiguration)
{
var typesInThisAssembly = typeof(AutoMapperExtensions).Assembly.GetExportedTypes();
CreateMapsForSourceTypes(configuration, typesInThisAssembly.Where(filter), destinationType, mappingConfiguration);
}
public static void CreateMapsForSourceTypes(this IConfiguration configuration, IEnumerable<Type> typeSource, Func<Type, Type> destinationType, Action<IMappingExpression, Type, Type> mappingConfiguration)
{
foreach (var type in typeSource)
{
var destType = destinationType(type);
if (destType == null) continue;
var mappingExpression = configuration.CreateMap(type, destType);
mappingConfiguration(mappingExpression, type, destType);
}
}
public static IMappingExpression MapViewUrls(this IMappingExpression expression, Type sourceType, Type destinationType)
{
if (destinationType.GetProperty(DovetailViewExtensions.URL_SUFFIX) != null)
{
expression.ForMember(DovetailViewExtensions.URL_SUFFIX, map => map.ResolveUsing<UrlValueResolver>());
}
var entityProperties = destinationType.GetProperties().Where(p => p.PropertyType == typeof(string) && p.Name.EndsWith(DovetailViewExtensions.URL_SUFFIX) && p.Name != DovetailViewExtensions.URL_SUFFIX);
foreach (var prop in entityProperties)
{
var sourcePropertyName = prop.Name.Replace(DovetailViewExtensions.URL_SUFFIX, string.Empty);
var destPropertyName = prop.Name;
expression.ForMember(destPropertyName, map => map.ResolveUsing<UrlValueResolver>().FromMember(sourcePropertyName));
}
return expression;
}
public static IMappingExpression MapDisplayValues(this IMappingExpression expression, Type sourceType, Type destinationType)
{
const string DISPLAY_SUFFIX = "Display";
var entityProperties = destinationType.GetProperties().Where(p => p.PropertyType == typeof(string) && p.Name.EndsWith(DISPLAY_SUFFIX));
foreach (var prop in entityProperties)
{
var sourcePropertyName = prop.Name.Replace(DISPLAY_SUFFIX, string.Empty);
var destPropertyName = prop.Name;
expression.ForMember(destPropertyName, map => map.ResolveUsing<ListValueResolver>().FromMember(sourcePropertyName));
}
return expression;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment