Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/Flattening.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,11 +145,11 @@ destination.Name.ShouldBe("name");
destination.Description.ShouldBe("description");
destination.Title.ShouldBe("title");
```
So this allows you to reuse the configuration in the existing maps for the child types `InnerSource` and `OtherInnerSource` when mapping the parent types `Source` and `Destination`. It works in a similar way to [mapping inheritance](Mapping-inheritance.html), but it uses composition, not inheritance.
So this allows you to reuse the configuration in the existing map for the child types `InnerSource` and `OtherInnerSource` when mapping the parent types `Source` and `Destination`. It works in a similar way to [mapping inheritance](Mapping-inheritance.html), but it uses composition, not inheritance.

The order of the parameters in the `IncludeMembers` call is relevant. When mapping a destination member, the first match wins, starting with the source object itself and then with the included child objects in the order you specified. So in the example above, `Name` is mapped from the source object itself and `Description` from `InnerSource` because it's the first match.

Note that this matching is static, it happens at configuration time, not at `Map` time, and the runtime types of the child objects are not considered.
Note that this matching is static, it happens at configuration time, not at `Map` time, so the runtime types of the child objects are not considered.

IncludeMembers integrates with `ReverseMap`. An included member will be reversed to
```c#
Expand Down
5 changes: 4 additions & 1 deletion src/AutoMapper/Configuration/ConfigurationValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,10 @@ private void DryRunTypeMap(ICollection<TypeMap> typeMapsChecked, TypePair types,
if(mapperToUse is IObjectMapperInfo mapperInfo)
{
var newTypePair = mapperInfo.GetAssociatedTypes(types);
DryRunTypeMap(typeMapsChecked, newTypePair, null, memberMap);
if (newTypePair != types)
{
DryRunTypeMap(typeMapsChecked, newTypePair, null, memberMap);
}
}
}
}
Expand Down
14 changes: 2 additions & 12 deletions src/AutoMapper/Configuration/MapperConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -300,25 +300,15 @@ private TypeMap GetTypeMap(TypePair initialTypes)
static List<Type> GetTypeInheritance(Type type)
{
var interfaces = type.GetInterfaces();
var lastIndex = interfaces.Length - 1;
var types = new List<Type>(interfaces.Length + 2) { type };
Type baseType = type;
while ((baseType = baseType.BaseType) != null)
{
types.Add(baseType);
foreach (var interfaceType in baseType.GetInterfaces())
{
var interfaceIndex = Array.LastIndexOf(interfaces, interfaceType);
if (interfaceIndex != lastIndex)
{
interfaces[interfaceIndex] = interfaces[lastIndex];
interfaces[lastIndex] = interfaceType;
}
}
}
foreach (var interfaceType in interfaces)
for(int index = interfaces.Length - 1; index >= 0; index--)
{
types.Add(interfaceType);
types.Add(interfaces[index]);
}
return types;
}
Expand Down
4 changes: 3 additions & 1 deletion src/AutoMapper/Internal/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,10 @@ public static Type GetGenericInterface(this Type type, Type genericInterface)
{
return type;
}
foreach (var interfaceType in type.GetInterfaces())
var interfaces = type.GetInterfaces();
for(int index = interfaces.Length - 1; index >= 0; index--)
{
var interfaceType = interfaces[index];
if (interfaceType.IsGenericType(genericInterface))
{
return interfaceType;
Expand Down
30 changes: 25 additions & 5 deletions src/AutoMapper/Mappers/CollectionMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,22 @@ Expression MapReadOnlyCollection(Type genericCollectionType, Type genericReadOnl
Expression MapCollectionCore(Expression destExpression)
{
var destinationType = destExpression.Type;
MethodInfo addMethod;
bool isIList, mustUseDestination = memberMap is { MustUseDestination: true };
Type destinationCollectionType, destinationElementType;
var sourceType = sourceExpression.Type;
MethodInfo addMethod = null;
bool isIList = false, mustUseDestination = memberMap is { MustUseDestination: true };
Type destinationCollectionType = null, destinationElementType = null;
GetDestinationType();
var passedDestination = Variable(destExpression.Type, "passedDestination");
var newExpression = Variable(passedDestination.Type, "collectionDestination");
var sourceElementType = sourceExpression.Type.GetICollectionType()?.GenericTypeArguments[0] ?? GetEnumerableElementType(sourceExpression.Type);
var sourceElementType = GetEnumerableElementType(sourceType);
if (destinationCollectionType == null || (sourceType == sourceElementType && destinationType == destinationElementType))
{
if (destinationType.IsAssignableFrom(sourceType))
{
return sourceExpression;
}
throw new NotSupportedException($"Unknown collection. Consider a custom type converter from {sourceType} to {destinationType}.");
}
var itemParam = Parameter(sourceElementType, "item");
var itemExpr = configurationProvider.MapExpression(profileMap, new TypePair(sourceElementType, destinationElementType), itemParam);
Expression destination, assignNewExpression;
Expand All @@ -78,25 +87,36 @@ Expression MapCollectionCore(Expression destExpression)
return CheckContext();
void GetDestinationType()
{
var immutableCollection = !mustUseDestination && destinationType.IsValueType;
if (immutableCollection)
{
return;
}
destinationCollectionType = destinationType.GetICollectionType();
destinationElementType = destinationCollectionType?.GenericTypeArguments[0] ?? GetEnumerableElementType(destinationType);
isIList = destExpression.Type.IsListType();
if (destinationCollectionType == null)
{
if (isIList)
{
destinationCollectionType = typeof(IList);
addMethod = IListAdd;
destinationElementType = GetEnumerableElementType(destinationType);
}
else
{
if (!destinationType.IsInterface)
{
return;
}
destinationElementType = GetEnumerableElementType(destinationType);
destinationCollectionType = typeof(ICollection<>).MakeGenericType(destinationElementType);
destExpression = Convert(mustUseDestination ? destExpression : Null, destinationCollectionType);
addMethod = destinationCollectionType.GetMethod("Add");
}
}
else
{
destinationElementType = destinationCollectionType.GenericTypeArguments[0];
addMethod = destinationCollectionType.GetMethod("Add");
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/AutoMapper/QueryableExtensions/ProjectionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ bool OverMaxDepth()
}
void ProjectProperties()
{
foreach (var propertyMap in typeMap.PropertyMaps.Where(pm => pm.CanResolveValue && pm.DestinationMember.CanBeSet()).OrderBy(pm => pm.DestinationName))
foreach (var propertyMap in typeMap.PropertyMaps.Where(pm => pm.CanResolveValue && pm.DestinationMember.CanBeSet()).OrderBy(pm => pm.DestinationMember.MetadataToken))
{
var propertyProjection = TryProjectMember(propertyMap, propertyMap.ExplicitExpansion);
if (propertyProjection != null)
Expand Down
52 changes: 51 additions & 1 deletion src/UnitTests/CollectionMapping.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,61 @@
using Xunit;
using Shouldly;
using System.Collections;
using System.Reflection;
using AutoMapper.Internal;
using System.Collections.Immutable;

namespace AutoMapper.UnitTests
{
public class ImmutableCollection : AutoMapperSpecBase
{
class Source
{
public string Value { get; set; }
}
class Destination
{
public ImmutableArray<int> Value { get; set; }
}
protected override MapperConfiguration CreateConfiguration() => new(c =>
c.CreateMap<Source, Destination>().ForMember(d=>d.Value, o=>o.MapFrom(_=>ImmutableArray.Create<int>())));
[Fact]
public void Should_work() => Map<Destination>(new Source()).Value.ShouldBeOfType<ImmutableArray<int>>();
}
public class AssignableCollection : AutoMapperSpecBase
{
class Source
{
public string Value { get; set; }
}
class Destination
{
public MyJObject Value { get; set; }
}
class MyJObject : IEnumerable
{
public IEnumerator GetEnumerator() => throw new NotImplementedException();
}
protected override MapperConfiguration CreateConfiguration() => new(c =>
c.CreateMap<Source, Destination>().ForMember(d=>d.Value, o=>o.MapFrom(_=>new MyJObject())));
[Fact]
public void Should_work() => Map<Destination>(new Source()).Value.ShouldBeOfType<MyJObject>();
}
public class RecursiveCollection : AutoMapperSpecBase
{
class Source
{
public string Value { get; set; }
}
class Destination
{
public MyJObject Value { get; set; }
}
class MyJObject : List<MyJObject>{}
protected override MapperConfiguration CreateConfiguration() => new(c =>
c.CreateMap<Source, Destination>().ForMember(d=>d.Value, o=>o.MapFrom(_=>new MyJObject())));
[Fact]
public void Should_work() => Map<Destination>(new Source()).Value.ShouldBeOfType<MyJObject>();
}
public class AmbigousMethod : AutoMapperSpecBase
{
public class Source
Expand Down