Skip to content

Commit 340b298

Browse files
committed
report unknown collection types at map time
1 parent 4c8207c commit 340b298

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

src/AutoMapper/Mappers/CollectionMapper.cs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,9 @@ Expression MapCollectionCore(Expression destExpression)
4949
var sourceElementType = GetEnumerableElementType(sourceType);
5050
if (destinationCollectionType == null || (sourceType == sourceElementType && destinationType == destinationElementType))
5151
{
52-
if (destinationType.IsAssignableFrom(sourceType))
53-
{
54-
return sourceExpression;
55-
}
56-
throw new NotSupportedException($"Unknown collection. Consider a custom type converter from {sourceType} to {destinationType}.");
52+
return destinationType.IsAssignableFrom(sourceType) ?
53+
sourceExpression :
54+
Throw(Constant(new NotSupportedException($"Unknown collection. Consider a custom type converter from {sourceType} to {destinationType}.")), destinationType);
5755
}
5856
var itemParam = Parameter(sourceElementType, "item");
5957
var itemExpr = configuration.MapExpression(profileMap, new TypePair(sourceElementType, destinationElementType), itemParam);

src/UnitTests/CollectionMapping.cs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,25 @@
11
using System.Collections.Specialized;
22
using System.Collections.Immutable;
3-
43
namespace AutoMapper.UnitTests;
5-
4+
public class UnsupportedCollection : AutoMapperSpecBase
5+
{
6+
class Source
7+
{
8+
public MyList<DateTime> List { get; set; } = new();
9+
}
10+
class Destination
11+
{
12+
public MyList<int> List { get; set; }
13+
}
14+
class MyList<T> : IEnumerable
15+
{
16+
public IEnumerator GetEnumerator() => new List<T>.Enumerator();
17+
}
18+
protected override MapperConfiguration CreateConfiguration() => new(c => c.CreateMap<Source, Destination>());
19+
[Fact]
20+
public void ThrowsAtMapTime() => new Action(()=>Map<Destination>(new Source())).ShouldThrow<AutoMapperMappingException>()
21+
.InnerException.ShouldBeOfType<NotSupportedException>().Message.ShouldBe($"Unknown collection. Consider a custom type converter from {typeof(MyList<DateTime>)} to {typeof(MyList<int>)}.");
22+
}
623
public class When_mapping_interface_to_interface_readonly_set : AutoMapperSpecBase
724
{
825
public class Source

0 commit comments

Comments
 (0)