Skip to content

Commit

Permalink
Merge pull request MapsterMapper#37 from chaowlert/master
Browse files Browse the repository at this point in the history
Add descriptive exception when map immutable type
  • Loading branch information
eswann committed Feb 1, 2016
2 parents 154321f + 5b14a24 commit ec63d5a
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/Mapster.Tests/WhenMappingPrimitives.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,50 @@ public void ValueType_String_Object_Is_Always_Primitive()
targetDto.Obj.ShouldBeSameAs(sourceDto.Obj);
}

[Test]
public void Immutable_Class_With_No_Mapping_Should_Error()
{
try
{
TypeAdapterConfig.GlobalSettings.Clear();
TypeAdapterConfig<ImmutableA, ImmutableB>.NewConfig().Compile();
Assert.Fail();
}
catch (InvalidOperationException exception)
{
exception.ToString().Contains("MapWith").ShouldBeTrue();
}
}

[Test]
public void Able_To_Map_Immutable_Class_With_MapWith()
{
TypeAdapterConfig.GlobalSettings.Clear();
TypeAdapterConfig<ImmutableA, ImmutableB>.NewConfig()
.MapWith(src => new ImmutableB(src.Name))
.Compile();
}

public class ImmutableA
{
public ImmutableA(string name)
{
this.Name = name;
}

public string Name { get; }
}

public class ImmutableB
{
public ImmutableB(string name)
{
this.Name = name;
}

public string Name { get; }
}

public class TestA
{
public Byte[] Bytes { get; set; }
Expand Down
7 changes: 7 additions & 0 deletions src/Mapster/TypeAdapterSetter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@ public TypeAdapterSetter<TSource, TDestination> ConstructUsing(Expression<Func<T
public TypeAdapterSetter<TSource, TDestination> MapWith(Expression<Func<TSource, TDestination>> converterFactory)
{
Settings.ConverterFactory = arg => converterFactory;

if (Settings.ConverterToTargetFactory == null)
{
var dest = Expression.Parameter(typeof (TDestination));
Settings.ConverterToTargetFactory = arg => Expression.Lambda(converterFactory.Body, converterFactory.Parameters[0], dest);
}

return this;
}

Expand Down
4 changes: 4 additions & 0 deletions src/Mapster/Utils/ReflectionUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,10 @@ public static Expression BuildUnderlyingTypeConvertExpression(Expression source,
}
catch { }

if (srcType.GetInterfaces().All(type => type != typeof (IConvertible)))
throw new InvalidOperationException(
$"Cannot convert immutable type, please consider using 'MapWith' method to create mapping: TSource: {sourceType} TDestination: {destinationType}");

//using Convert
if (destType == typeof(bool))
return CreateConvertMethod("ToBoolean", srcType, destType, source);
Expand Down

0 comments on commit ec63d5a

Please sign in to comment.